Spring如何读取properties文件-创新互联
小编给大家分享一下Spring如何读取properties文件,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

我们都知道,Spring可以@Value的方式读取properties中的值,只需要在配置文件中配置
org.springframework.beans.factory.config.PropertyPlaceholderConfigurer
classpath:config.properties
那么在需要用到这些获取properties中值的时候,可以这样使用
@Value("${sql.name}")
private String sqlName;但是这有一个问题,我每用一次配置文件中的值,就要声明一个局部变量。有没有用代码的方式,直接读取配置文件中的值。
答案就是重写PropertyPlaceholderConfigurer
public class PropertyPlaceholder extends PropertyPlaceholderConfigurer {
private static Map propertyMap;
@Override
protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException {
super.processProperties(beanFactoryToProcess, props);
propertyMap = new HashMap();
for (Object key : props.keySet()) {
String keyStr = key.toString();
String value = props.getProperty(keyStr);
propertyMap.put(keyStr, value);
}
}
//static method for accessing context properties
public static Object getProperty(String name) {
return propertyMap.get(name);
}
} 在配置文件中,用上面的类,代替PropertyPlaceholderConfigurer
classpath:config.properties
这样在代码中就可以直接用编程方式获取
PropertyPlaceholder.getProperty("sql.name");如果是多个配置文件,配置locations属性
file:./jdbc.properties file:./module.config.properties classpath:jdbc.properties classpath*:*.config.properties
以上是“Spring如何读取properties文件”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注创新互联行业资讯频道!
分享名称:Spring如何读取properties文件-创新互联
网站路径:http://www.scyingshan.cn/article/gchih.html


咨询
建站咨询
