1.PropertyPlaceholderConfigurer了解
PropertyPlaceholderConfigurer是spring提供我们来把一些环境变量(数据库连接相关参数,文件路径等)统一管理起来,然后在bean中指定对应的变量的。但是往往开发环境,测试环境,生成环境的这些参数配置是不同的,那么我们如何使用PropertyPlaceholderConfigurer扩展来满足不同环境的配置需求,而不需要在不同环境需要修改代码或者配置。
2.PropertyPlaceholderConfigurer扩展类的编写
package com.wyf.core.bean;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.util.PropertyPlaceholderHelper;
public class PropertyPlaceholderConfigurerExt extends PropertyPlaceholderConfigurer{
private static Map<String,String> properties = new HashMap<String,String>();
@Override
protected void convertProperties(final Properties props) {
final Set<String> keys = props.stringPropertyNames();
for(final String key:keys){
final String value = props.getProperty(key);
this.properties.put(key, value);
}
super.convertProperties(props);
}
public static String getProperty(final String key) {
return properties.get(key);
}
}
3.测试代码
public class Test {
public static void main(String[] args) {
new ClassPathXmlApplicationContext("config/spring-all.xml");
String properties = PropertyPlaceholderConfigurerExt.getProperty("db.url");
System.out.println(properties);
}
}
import java.util.Map;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:config/spring-all.xml" })
public class PropertyPlaceHolderTest {
@Test
public void testMyPropertyPlaceHolder(){
String properties = PropertyPlaceholderConfigurerExt.getProperty("db.url");
System.out.println(properties);
}
}