获取Spring配置文件属性 https://my.oschina.net/vincentzhao/blog/792461
先看下我们平时是如何使用配置文件的:
1 2 3 4 5 6 7 8 |
<!--加载属性文件--> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <array> <value>file:/usr/heliConfig/payprovider/payprovider.cfg</value> </array> </property> </bean> |
在PropertyPlaceholderConfigurer类里并没有提供配置文件属性的get方法,但是通过调试发现loadProperties方法在执行完成之后,参数Properties会被赋值完成,那么可以通过重写该方法,获取属性值:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
package com.vincent; import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer; import java.io.IOException; import java.util.Properties; /** * Vincent 创建于 2016/11/22. */ public class Pro extends PropertyPlaceholderConfigurer { private Properties p; @Override protected void loadProperties(Properties props) throws IOException { super.loadProperties(props); p=props; Demo.p=p; } public Properties getP() { return p; } public void setP(Properties p) { this.p = p; } } |
1 2 3 4 5 6 7 8 9 10 11 12 |
package com.vincent; import java.util.Properties; /** * Vincent 创建于 2016/11/22. */ public class Demo { public static Properties p=null; } |
修改配置文件如下:
1 2 3 4 5 6 7 8 |
<!--加载属性文件--> <bean class="com.vincent.Pro"> <property name="locations"> <array> <value>file:/usr/heliConfig/payprovider/payprovider.cfg</value> </array> </property> </bean> |
通过以上示例,可以轻松获取属性文件,便于灵活使用