spring之PropertyPlaceholderConfigurer扩展

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); 
	}
}
4.测试结果







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值