Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Value is not injected

I'm trying to inject value from properties file into a spring configuration class as follows:

@Configuration
@EnableWebMvc
public class ImagesContext {
   @Autowired
   @Value("${some.property.com}")
   private String property;

   @Bean
   public MyClass getMyClass() {
      return new MyClass(property);
   }
}

But the property is not injected correctly. Instead, when I debug, I see that the property string contains ${some.property.com} and not the string value itself.

like image 555
Avi Avatar asked Jul 28 '14 10:07

Avi


1 Answers

The @Value annotation is processed by AutowiredAnnotationBeanPostProcessor which is typically registered if you have a <component-scan> or <annotation-config> configuration in XML (or directly with a bean definition). You need to add either of those, probably <annotation-config>

Add the following bean declaration in your Config class if not done already

@Bean
public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
    return new PropertySourcesPlaceholderConfigurer();
}

In order for @Value annotations to work PropertySourcesPlaceholderConfigurer should be registered. It is done automatically when using <context:property-placeholder> in XML, but should be registered as a static @Bean when using @Configuration.

like image 118
Ankur Singhal Avatar answered Sep 21 '22 11:09

Ankur Singhal