Have couple of fields annotated with @Value within the @Service Class. These fields are not getting populated properly and are null. Perhaps I overlooked something, I have pasted the relevant blocks of code below. Tried the alternative option env.getProperty() with same result.
The value of following properties in output are null.
package com.project.service.impl;
import org.springframework.beans.factory.annotation.Value
@Service("aService")
@PropertySource(value="classpath:app.properties")
public class ServiceImpl implements Service{
private Environment environment;
@Value("${list.size}")
private Integer list1;
@Value("${list2.size}")
private Integer list2Size;
@Autowired
public ServiceImpl(StringRedisTemplate stringTemplate){
this.stringTemplate = stringTemplate;
logger.info("TESTING 123: "+list1);
}
// ...
}
@EnableWebMvc
@ComponentScan(basePackages = {"com.project.service","..."})
@Configuration
public class ServletConfig extends WebMvcConfigurerAdapter {
// ...
@Bean
public static PropertySourcesPlaceholderConfigurer properties() {
PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
Resource[] resources = new ClassPathResource[] {
new ClassPathResource("app.properties")
};
propertyPlaceholderConfigurer.setLocations(resources);
propertyPlaceholderConfigurer.setIgnoreUnresolvablePlaceholders(true);
return propertyPlaceholderConfigurer;
}
}
@Value annotation can be used within classes annotated with @Configuration , @Component and other stereotype annotations like @Controller , @Service etc. The actual processing of @Value annotation is performed by BeanPostProcessor and so @Value cannot be used within BeanPostProcessor class types.
Spring @Value annotation is used to assign default values to variables and method arguments. We can read spring environment variables as well as system variables using @Value annotation.
Field Injection takes place after construction hence the NullPointer Exception. Solution is to annotate the constructor params with @Value e.g.
public ServiceImpl(StringRedisTemplate stringTemplate, @Value("${list.size}" Integer list1, ..){}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With