Spring MVC框架下在java代码中访问applicationContext.xml文件中配置的文件(可以用于读取配置文件内容)

时间:2023-09-29 12:41:14
<bean id="propertyConfigurer" class="com.****.framework.core.SpringPropertiesUtil"
lazy-init="false">
<property name="locations">
<list>
<value>classpath:config/sys.properties</value>
</list>
</property>
</bean>

applicationContext.xml文件中配置好sys.properties文件的路径 ↑↑↑↑

然后是springPropertiesUtil文件内容:

package com.****.framework.core;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer; import java.util.HashMap;
import java.util.Map;
import java.util.Properties; public class SpringPropertiesUtil extends PropertyPlaceholderConfigurer { private static Map<String, String> propertiesMap;
// Default as in PropertyPlaceholderConfigurer
private int springSystemPropertiesMode = SYSTEM_PROPERTIES_MODE_FALLBACK; @Override
public void setSystemPropertiesMode(int systemPropertiesMode) {
super.setSystemPropertiesMode(systemPropertiesMode);
springSystemPropertiesMode = systemPropertiesMode;
} @Override
protected void processProperties(ConfigurableListableBeanFactory beanFactory, Properties props) throws BeansException {
super.processProperties(beanFactory, props); propertiesMap = new HashMap<String, String>();
for (Object key : props.keySet()) {
String keyStr = key.toString();
String valueStr = resolvePlaceholder(keyStr, props, springSystemPropertiesMode);
propertiesMap.put(keyStr, valueStr);
}
}
public static String getProperty(String name) {
return propertiesMap.get(name).toString();
} public static String getProperty(String name,String def) {
String ret = propertiesMap.get(name);
if(StringUtils.isBlank(ret)){
return def;
}
return ret.toString();
} }

第三步是正题:在java代码中调用这个配置:

 SpringPropertiesUtil springPropertiesUtil = (SpringPropertiesUtil) applicationContext.getBean("propertyConfigurer");
return springPropertiesUtil.getProperty(key);