13

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; } } 
8
  • 1
    Please show the code for the class where you're using that service object. Commented Aug 13, 2014 at 23:13
  • Also include your imports... you could have the wrong @Value imported. Commented Aug 14, 2014 at 4:41
  • @JamieWhite Set ignoreUnresolvablePlaceholders to false so you can see if other properties are not found. where in your projectstucture is app.properties. Have you tried new ClassPathResource("/app.properties") Commented Aug 14, 2014 at 5:35
  • @Jens tried what you suggested but property is still 'null'. Commented Aug 14, 2014 at 5:52
  • @JamieWhite Can you please describe you project structure and post the app.propperties file? Commented Aug 14, 2014 at 5:55

1 Answer 1

21

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, ..){} 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.