1. 程式人生 > >用[email protected]註解實現常量功能

[email protected]註解實現常量功能

之前的部落格中提到過如何通過 java.util.ResourceBundle  java.util.Properties 類通過讀取 key-value檔案的形式實現常量功能。其實 spring 已經通過 @Value 註解實現,下面看看如何使用。

1.建立.properties檔案:

在如下目錄建立 keyvalue.properties 檔案 src/main/resources/META-INF/spring/keyvalue.properties,寫入如下內容:

test.value=iloveyou

2.配置檔案中將.properties檔案引入:

applicationContext.xml 配置檔案中加入如下內容:

1 2 3 4 5 6 7 8 9 10 <bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean"> <property name="locations"> <list> <value>classpath*:META-INF/spring/*.properties</value> </list> </property> </bean>
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer"> <property name="properties" ref="configProperties"/> </bean>

這裡需要注意的是兩個<bean>  id 都可以自定義,第一個<property> 中指定 .properties 檔案的路徑,第二個<property> 中的 ref 要和第一個

<bean>  id 對應。

3.使用@Value註解:

   引入Value 類,在需要取值的屬性上方加上 @Value 註解,其中註明的 configProperties 和第一個 <bean>中的 id 和第二個 <property> 中的 ref 屬性對應,[] 中對應 .properties 檔案中相應的 key 值:

1 2 3 4 5 6 7 import org.springframework.beans.factory.annotation.Value; @Value("#{configProperties['test.value']}") private String testValue; System.out.println("TestValue Is: " + testValue); // 輸出結果  Test Value Is: iloveyou 出處:http://xitongjiagoushi.blog.51cto.com/9975742/1659051