這里介紹兩種在代碼中獲取properties文件屬性的方法。
使用@Value注解獲取properties文件屬性:
1.因為在下面要用到Spring的<util />配置,所以,首先要在applicationContext.xml中引入其對應的命名空間:
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd"
2.創建properties文件並增加內容:
#搜索服務地址
solrURL=http://localhost:8080/solr
3.在applicationContext.xml中加入以下的配置:
<!-- 添加注解驅動 --> <mvc:annotation-driven /> <!-- 注解默認掃描的包路徑 --> <context:component-scan base-package="com.wdcloud.solr" /> <!-- 載入配置文件 --> <util:properties id="constants" location="classpath:config/statics.properties"/>
4.使用@Value注解,在java類中獲取properties文件中的值(這里constants對應上面的id):
@Value("#{constants.solrURL}")
public String testUrl;
@RequestMapping(value = "/test", method = RequestMethod.GET)
@ResponseBody
public Result queryTest() {
System.out.println("testUrl:" + testUrl);
}
測試結果:

使用@Value獲取屬性值的方法有一個問題,我每用一次配置文件中的值,就要聲明一個局部變量,即不能使用static和final來修飾變量。而第二種方法可以解決這個問題。
重寫PropertyPlaceholderConfigurer:
1.通常我們使用spring的PropertyPlaceholderConfigurer類來讀取配置信息,這里我們需要重寫它:
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 String getProperty(String name) { return propertyMap.get(name); } }
2.在applicationContext.xml中加入以下的配置:
<!-- 加載properties文件配置信息 --> <bean scope="singleton" id="propertyConfigurer" class="com.wdcloud.solr.util.PropertyPlaceholder"> <property name="locations"> <list> <value>classpath*:config/statics.properties</value> </list> </property> </bean>
3.使用PropertyPlaceholder.getProperty方法獲取屬性值:
public static final String solrURL = PropertyPlaceholder.getProperty("solrURL"); @RequestMapping(value = "/test", method = RequestMethod.GET) @ResponseBody public Result queryTest() { System.out.println(solrURL); }
測試結果:

參考:
http://1358440610-qq-com.iteye.com/blog/2090955
http://www.cnblogs.com/Gyoung/p/5507063.html
