Spring ${} is not working in @Value
By:Roy.LiuLast updated:2019-08-17
A simple Spring @PropertySource example to read a properties file.
db.properties
db.driver=oracle.jdbc.driver.OracleDriver
AppConfig.java
@Configuration @PropertySource("classpath:db.properties") public class AppConfig { @Value("${db.driver}") private String driver;
But the property placeholder ${} is unable to resolve in @Value, if print out the driver variable, it will display string ${db.driver} directly, instead of “oracle.jdbc.driver.OracleDriver”.
Solution
To resolve ${} in Spring @Value, you need to declare a STATIC PropertySourcesPlaceholderConfigurer bean manually. For example :
AppConfig.java
import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.context.support.PropertySourcesPlaceholderConfigurer; @Configuration @PropertySource("classpath:db.properties") public class AppConfig { @Value("${db.driver}") private String driver; @Bean public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() { return new PropertySourcesPlaceholderConfigurer();
For XML configuration, Spring will help you to register PropertySourcesPlaceholderConfigurer automatically.
<util:properties location="classpath:db.properties"/>
Note
Read this Spring JIRA SPR-8539
Read this Spring JIRA SPR-8539
Note
You may interest at this Spring @PropertySource example
You may interest at this Spring @PropertySource example
From:一号门
COMMENTS