重写PropertyPlaceholderConfigurer类达到使用静态方法来获取配置参数值

在spring里本身是没有提供这类方法的。所以我们只能通过重写一些类来达到我们想要的效果比如我之前的文章《Java中Spring的BeanUtil工具类》是通过实现 BeanFactoryAware 类来达到静态...

在spring里本身是没有提供这类方法的。

所以我们只能通过重写一些类来达到我们想要的效果

比如我之前的文章《实现BeanFactoryAware来达到Spring静态方法获取Bean对象的BeanUtil工具类》是通过实现 BeanFactoryAware 类来达到静态根据beanName来获取Bean实例的。

那首先我们要写一个PropertyUtil继承PropertyPlaceholderConfigurer

代码如下:

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

import java.util.Properties;

/**
 * 
 * @author hellojava.com
 *
 */
public class PropertyUtil extends PropertyPlaceholderConfigurer {

    private static Properties props;       // 存取properties配置文件key-value结果

    @Override
    protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props)
                            throws BeansException {
        super.processProperties(beanFactoryToProcess, props);
        this.props = props;
    }

    public static String getProperty(String key){
        return props.getProperty(key);
    }

    public static String getProperty(String key, String defaultValue) {
        return props.getProperty(key, defaultValue);
    }

    public Object setProperty(String key, String value) {
        return this.props.setProperty(key, value);
    }
}


然后我们要在Spring的配置xml文件里去改写properties的初始化容器类

<bean id="propertyConfigurer" class="com.gb.pay.common.util.PropertyUtil">
	    <property name="locations">
			<list>
				<value>classpath:configure.properties</value>	
			</list>
	     </property>		
</bean>


我们在configure.properties里增加一个配置

pay.mysql.driverClassName=com.mysql.jdbc.Driver


最后我们写一个测试类来测试我们的PropertyUtil

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import junit.framework.TestCase;

public class PropertyUtilTester extends TestCase {
	public void setUp() throws Exception {
		
		String[] locations = { "applicationContext.xml" };
		ApplicationContext context = new ClassPathXmlApplicationContext(
				locations);
	}
	
	public void testGetProperty(){
		String className =PropertyUtil.getProperty("pay.mysql.driverClassName");
		System.out.println(className);
	}
	
}


最终输出结果:

QQ截图20171020165421.jpg

  • 发表于 2017-10-20 16:54
  • 阅读 ( 4355 )
  • 分类:J2EE框架

条评论

请先 登录 后评论
不写代码的码农
三叔

422 篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除