@Value not resolved when using @PropertySource annotation. How to configure PropertySourcesPlaceholderConfigurer?
I have following configuration class:
@Configuration
@PropertySource(name = "props", value = "classpath:/app-config.properties")
@ComponentScan("service")
public class AppConfig {
and I have service with property:
@Component
public class SomeService {
@Value("#{props['some.property']}") private String someProperty;
I receive error when I want to test the AppConfig configuration class with
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'someService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private java.lang.String service.SomeService.someProperty; nested exception is org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.expression.spel.SpelEvaluationException: EL1008E:(pos 0): Field or property 'props' cannot be found on object of type 'org.springframework.beans.factory.config.BeanExpressionContext'
The issue is documented in SPR-8539
but anyway I cannot figure out how to configure PropertySourcesPlaceholderConfigurer to get it work.
Edit 1
This approach works well with xml configuration
<util:properties id="props" location="classpath:/app-config.properties" />
but I want to use java for configuration.
as @cwash said;
@Configuration
@PropertySource("classpath:/test-config.properties")
public class TestConfig {
@Value("${name}")
public String name;
//You need this
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
If you use @PropertySource, properties have to be retrieved with:
@Autowired
Environment env;
// ...
String subject = env.getProperty("mail.subject");
If you want to retrieve with @Value("${mail.subject}")
, you have to register the prop placeholder by xml.
Reason: https://jira.springsource.org/browse/SPR-8539
I found the reason @value
was not working for me is, @value
requires PropertySourcesPlaceholderConfigurer
instead of a PropertyPlaceholderConfigurer
. I did the same changes and it worked for me, I am using spring 4.0.3 release. I configured this using below code in my configuration file.
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
Don't you need a method on your @Configuration class that returns PropertySourcesPlaceholderConfigurer, annotated @Bean and is static, to register any @PropertySource with Spring?
http://www.baeldung.com/2012/02/06/properties-with-spring/#java
https://jira.springsource.org/browse/SPR-8539