SpringMVC 加载配置文件

填写配置文件

里面的内容格式的话是 key=value 形式,例如:

1
2
3
4
#配置1
SEND_MOBILE_TIMES=5
#配置2
SEND_IP_TIMES=10

新建一个配置文件类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class SystemProperty extends PropertyPlaceholderConfigurer {

private static Map<String, String> map;

@Override
protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess,Properties props) throws BeansException {

super.processProperties(beanFactoryToProcess, props);
map = new HashMap<String, String>();
for (Object key : props.keySet()) {
String keyStr = key.toString();
String value = props.getProperty(keyStr);
map.put(keyStr, value);
}
}

public static String getContextProperty(String name) {
return map.get(name);
}
}

在springmvc-servlet.xml的配置文件里添加这个bean扫描

1
2
3
4
5
6
7
8
9
<!-- 配置文件注入 class 填你的包名路径,如果有多个配置文件则可以多添加一个value-->
<bean id="SystemProperty" class="com.xx.xx.SystemProperty">
<property name="locations">
<list>
<value>classpath:xxx1.properties</value>
<value>classpath:jdbc.properties</value>
</list>
</property>
</bean>

获取配置文件的值

直接通过key调用这个方法就能拿到配置文件的值了。

1
SystemProperty.getContextProperty("SEND_MOBILE_TIMES");

JavaEE SpringMVC