码迷,mamicode.com
首页 > 编程语言 > 详细

Spring – ${} is not working in @Value--转载

时间:2015-04-10 17:02:39      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:

原文:http://www.mkyong.com/spring/spring-is-not-working-in-value/

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 STATICPropertySourcesPlaceholderConfigurer 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 PropertySourcesPlaceholderConfigurerautomatically.

<util:properties location="classpath:db.properties"/>

 

Spring – ${} is not working in @Value--转载

标签:

原文地址:http://www.cnblogs.com/davidwang456/p/4414712.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!