Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Value Property inside @Service Class is Null

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;
    }
}
like image 690
Jamie White Avatar asked Aug 13 '14 22:08

Jamie White


People also ask

Can we use @value in service class?

@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.

What is @value annotation is used for?

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.


1 Answers

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, ..){}
like image 186
Jamie White Avatar answered Sep 30 '22 02:09

Jamie White