在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);
}
}
最终输出结果: