Spring读取properties资源文件
我们知道可以通过读取资源文件流后加载到Properties对象,再使用该对象方法来获取资源文件。现在介绍下利用Spring内置对象来读取资源文件。
系统启动时加载资源文件链路:web.xml --> spring-core.xml --> sysconfig.properties
接下来直接看代码吧
web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-core.xml</param-value>
</context-param>
spring-core.xml
<!-- 加载properties里的内容 -->
<bean id="PropertyConfig" class="com.wulinfeng.PropertiesConfig">
<property name="ignoreUnresolvablePlaceholders" value="true" />
<property name="locations">
<list>
<value>classpath:sysconfig.properties</value>
</list>
</property>
<property name="fileEncoding">
<value>UTF-8</value>
</property>
</bean>
PropertiesConfig.java
public class PropertiesConfig extends PropertyPlaceholderConfigurer { private static Map<String, String> propertyMap; @Override protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException { super.processProperties(beanFactoryToProcess, props); if (propertyMap == null || propertyMap.size() == 0) { propertyMap = new HashMap<String, String>(); for (Object key : props.keySet()) { String keyStr = key.toString(); String value = props.getProperty(keyStr); propertyMap.put(keyStr, value); } } } public static String getProperty(String name,String def) { if (propertyMap == null || propertyMap.isEmpty() || null == propertyMap.get(name)) { return def; } return propertyMap.get(name); } public static String getProperty(String name) { if (propertyMap == null || propertyMap.isEmpty()) { return null; } return propertyMap.get(name); } }
注意这里需要继承Spring的PropertyPlaceholderConfigurer类。
浙公网安备 33010602011771号