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

在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的初始化容器类

classpath:configure.properties

我们在configure.properties里增加一个配置pay.mysql.driverClassName=com.mysql.jdbc.Driver

最后我们写一个测试类来测试我们的PropertyUtilimport 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);

}

}

最终输出结果:

1f80ad1ab45355b7b6b8a53b8d71f0de.png

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值