2

@Value アノテーションを使用しようとすると、値が null になる状況があります。

これは大規模なプロジェクトの一部であり、どの部分が必要なのかわかりません。Java 注釈 (xml ファイルなし) と Spring ブートを使用しています。


@Configuration
@EnableAutoConfiguration
@EnableConfigurationProperties
@ComponentScan
public class RESTApplication {
    public static void main(String[] args) {
        SpringApplication.run(RESTApplication.class, args);
    }
}

application.properties には以下が含まれます。

maxuploadfilesize=925000000

一部のWebサイトでそうするように言及されているように、PropertySourcesPlaceholderConfigurerを作成しようとしました。

@Configuration
public class AppConfig {
    @Bean
    public static PropertySourcesPlaceholderConfigurer properties() {
        return new PropertySourcesPlaceholderConfigurer();
    }
}

これを使用しようとしているクラスは次のとおりです。

@Component
public class MyClass {
    @Value("${maxuploadfilesize}")
    String maxFileUploadSize;

    public String getMaxFileUploadSize() {
        return maxFileUploadSize;
    }

    public void setMaxFileUploadSize(String maxFileUploadSize) {
        this.maxFileUploadSize = maxFileUploadSize;
    }
}

ただし、実行時には、maxFileUploadSize は常に null です。PropertySourcesPropertyResolver が application.properties ファイル内で正しい値を見つけたように見える以下のデバッグ コメントに注意してください。

2015-06-10 13:50:20.906 DEBUG 21108 --- [           main] o.s.c.e.PropertySourcesPropertyResolver  : Searching for key 'maxuploadfilesize' in [applicationConfig: [classpath:/application.properties]]
2015-06-10 13:50:20.906 DEBUG 21108 --- [           main] o.s.c.e.PropertySourcesPropertyResolver  : Found key 'maxuploadfilesize' in [applicationConfig: [classpath:/application.properties]] with type [String] and value '925000000'
4

1 に答える 1

4

MyClass が SpringBean として処理されていないようです。つまり、@Value アノテーションが処理されていません。のようなデフォルト値を指定することで確認できます @Value("${maxuploadfilesize:'100'}")。値がまだ null の場合は、MyClass が SpringBean としてインスタンス化されていないことがわかります。

@Component で注釈が付けられているため、単純に注入できるはずです @Autowired private MyClass myclass;

于 2015-06-11T08:33:55.227 に答える