有些時候,我們需要以Spring代碼直接讀取properties配置文件,那么我們要如何操作呢?下面我們來看看具體內容。
我們都知道,Spring可以@Value的方式讀取properties中的值,只需要在配置文件中配置
org.springframework.beans.factory.config.PropertyPlaceholderConfigurer
1
2
3
4
5
|
< bean id = "propertyConfigurer" class = "org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" > < property name = "location" > < value >classpath:config.properties</ value > </ property > </ bean > |
那么在需要用到這些獲取properties中值的時候,可以這樣使用
1
2
|
@Value ( "${sql.name}" ) private String sqlName; |
但是這有一個問題,我每用一次配置文件中的值,就要聲明一個局部變量。有沒有用代碼的方式,直接讀取配置文件中的值。
答案就是重寫PropertyPlaceholderConfigurer
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
public class PropertyPlaceholder extends PropertyPlaceholderConfigurer { private static Map<String,String> propertyMap; @Override protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException { super .processProperties(beanFactoryToProcess, props); propertyMap = new HashMap<String, String>(); 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
1
2
3
4
5
|
< bean id = "propertyConfigurer" class = "com.gyoung.mybatis.util.PropertyPlaceholder" > < property name = "location" > < value >classpath:config.properties</ value > </ property > </ bean > |
這樣在代碼中就可以直接用編程方式獲取
1
|
PropertyPlaceholder.getProperty( "sql.name" ); |
如果是多個配置文件,配置locations屬性
1
2
3
4
5
6
7
8
9
10
11
12
|
< bean id = "propertyConfigurer" class = "com.gyoung.mybatis.util.PropertyPlaceholder" > < property name = "ignoreResourceNotFound" value = "true" /> < property name = "locations" > < list > < value >file:./jdbc.properties</ value > < value >file:./module.config.properties</ value > < value >classpath:jdbc.properties</ value > < value >classpath*:*.config.properties</ value > </ list > </ property > </ bean > |
總結
以上就是本文關于Spring用代碼來讀取properties文件實例解析的全部內容,希望對大家有所幫助。如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
原文鏈接:https://www.cnblogs.com/Gyoung/p/5507063.html