@Value Property inside class @Service - Null

There are several fields annotated with @Value in the @Service class. These fields are not filled out properly and are zero. Maybe I missed something, I inserted the corresponding blocks of code below. Tried an alternative variant of env.getProperty () with the same result.

The value of the following output properties: 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;
    }
}
+4
source share
1 answer

Field injection occurs after construction, therefore, a NullPointer exception. The solution is to annotate the constructor parameters with @Value, for example.

public ServiceImpl(StringRedisTemplate stringTemplate, @Value("${list.size}" Integer list1, ..){}
+10
source

All Articles