Spring通過@Value註解自動匯入配置檔案的幾種方式
阿新 • • 發佈:2019-02-05
場景
假如有以下屬性檔案dev.properties, 需要注入下面的tag
tag=123
需要宣告的是:在使用@Value 註解 注入引數時,在當前類需要給該屬性提供Setter 方法!!
1.通過PropertyPlaceholderConfigurer<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="dev.properties" />
</bean>
程式碼:
@Value("${tag}") private String tag;
2.通過PreferencesPlaceholderConfigurer
<bean id="appConfig" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
<property name="location" value="dev.properties" />
</bean>
程式碼:
@Value("${tag}")
private String tag;
與上面 PropertyPlaceholderConfigurer 用法 相同!
3.通過PropertiesFactoryBean
<bean id="config" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="location" value="dev.properties" />
</bean>
程式碼:
@Value("#{config['tag']}")
private String tag;
通過util:properties效果同PropertiesFactoryBean一樣
程式碼:
其他方式@Value("#{config['tag']}") private String tag;
有時也可以不通過檔案,直接寫字面量
<bean id="appConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<!--<property name="location" value="classpath:${env}.properties" />-->
<property name="properties">
<props>
<prop key="tag">123</prop>
</props>
</property>
</bean>
程式碼:
@Value("${tag}")
private String tag;
另外還有一種方式:Spring中有個<context:property-placeholder location=""/>標籤,可以用來載入properties配置檔案,location是配置檔案的路徑,我們現在在工程目錄的src下新建一個conn.properties檔案,裡面寫上上面dataSource的配置:<context:property-placeholder location="classpath:conn.properties"/><!-- 載入配置檔案 -->
<context:property-placeholder location=""/>標籤也可以用下面的<bean>標籤來代替,<bean>標籤我們更加熟悉,可讀性更強<!-- 與上面的配置等價,下面的更容易理解 -->
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations"> <!-- PropertyPlaceholderConfigurer類中有個locations屬性,接收的是一個數組,即我們可以在下面配好多個properties檔案 -->
<array>
<value>classpath:conn.properties</value>
</array>
</property>
</bean>
雖然看起來沒有上面的<context:property-placeholder location=""/>簡潔,但是更加清晰,建議使用後面的這種。但是這個只限於xml的方式,即在beans.xml中用${key}獲取配置檔案中的值value。