@Value is always null

8.1k views Asked by At

I have a situation where my attempt to use a @Value annotation results in the value being a null.

This is part of a large project and I'm not sure which parts of it are needed. I am using Java anotations (no xml file) and Spring boot.


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

application.properties contains:

maxuploadfilesize=925000000

I did try to create a PropertySourcesPlaceholderConfigurer as some websites mentioned to do so.

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

Here is the class attempting to use it:

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

    public String getMaxFileUploadSize() {
        return maxFileUploadSize;
    }

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

However at runtime, maxFileUploadSize is always null. Note the below debug comment where PropertySourcesPropertyResolver seemed to find its correct value within the application.properties file.

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'
1

There are 1 answers

0
Hansjoerg Wingeier On

It looks like MyClass was not processed as SpringBean, which would mean, that the @Value-annotation was not processed. You could check that with providing a default value, like @Value("${maxuploadfilesize:'100'}"). If the value is still null, then you know, that MyClass is not instantiated as a SpringBean.

Since it is annotated with @Component, you should be able to simply inject it with @Autowired private MyClass myclass;