在項目中如果有些參數經常需要修改,或者後期可能需要修改,那我們最好把這些參數放到properties文件中,源代碼中讀取properties裏面的配置,這樣後期只需要改動properties文件即可,不需要修改源代碼,這樣更加方便。在Spring中也可以這麼做,而且Spring有兩種加載properties文件的方式:基於xml方式和基於註解方式。下面分別討論下這兩種方式。
1. 通過xml方式加載properties文件
我們以Spring實例化dataSource爲例,我們一般會在beans.xml文件中進行如下配置:
-
-
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
-
<property name="driverClass" value="com.mysql.jdbc.Driver" />
-
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/shop" />
-
<property name="user" value="root" />
-
<property name="password" value="root" />
-
</bean>
現在如果我們要改變dataSource,我們就得修改這些源代碼,但是我們如果使用properties文件的話,只需要修改那裏面的即可,就不管源代碼的東西了。那麼如何做呢?
Spring中有個<context:property-placeholder location=""/>標籤,可以用來加載properties配置文件,location是配置文件的路徑,我們現在在工程目錄的src下新建一個conn.properties文件,裏面寫上上面dataSource的配置:
-
dataSource=com.mchange.v2.c3p0.ComboPooledDataSource
-
driverClass=com.mysql.jdbc.Driver
-
jdbcUrl=jdbc\:mysql\://localhost\:3306/shop
-
user=root
-
password=root
現在只需要在beans.xml中做如下修改即可:
-
<context:property-placeholder location="classpath:conn.properties"/>
-
-
-
<bean id="dataSource" class="${dataSource}">
-
<property name="driverClass" value="${driverClass}" />
-
<property name="jdbcUrl" value="${jdbcUrl}" />
-
<property name="user" value="${user}" />
-
<property name="password" value="${password}" />
-
</bean>
<context:property-placeholder location=""/>標籤也可以用下面的<bean>標籤來代替,<bean>標籤我們更加熟悉,可讀性更強:
-
-
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
-
<property name="locations">
-
<array>
-
<value>classpath:conn.properties</value>
-
</array>
-
</property>
-
</bean>
雖然看起來沒有上面的<context:property-placeholder location=""/>簡潔,但是更加清晰,建議使用後面的這種。但是這個只限於xml的方式,即在beans.xml中用${key}獲取配置文件中的值value。
2. 通過註解方式加載properties文件
還有一種就是通過註解的方式,在java代碼中使用@Value註解來加載配置文件中的值。
我們來看一個例子:假如我們要在程序中獲取某個文件的絕對路徑,我們很自然會想到不能在程序中寫死,那麼我們也可以卸載properties文件中。還是在src目錄下新建一個public.properties文件,假設裏面寫了一條記錄:
-
filePath=E\:\\web\\apache-tomcat-8.0.26\\webapps\\E_shop\\image
如果想在java代碼中通過註解來獲取這個filePath的話,首先得在beans.xml文件中配置一下註解的方式:
-
-
<bean id="prop" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
-
<property name="locations"><!-- 這裏是PropertiesFactoryBean類,它也有個locations屬性,也是接收一個數組,跟上面一樣
-
<array>
-
<value>classpath:public.properties</value>
-
</array>
-
</property>
-
</bean>
現在我們可以在java代碼中使用註解來獲取filePath的值了:
-
@Component("fileUpload")
-
public class FileUploadUtil implements FileUpload {
-
-
private String filePath;
-
@Value("#{prop.filePath}")
-
-
public void setFilePath(String filePath) {
-
System.out.println(filePath);
-
this.filePath = filePath;
-
}
注意要有set方法才能被注入進來,註解寫在set方法上即可。在setFilePath方法中通過控制檯打印filePath是爲了在啓動tomcat的時候,觀察控制檯有沒有輸出來,如果有,說明Spring在啓動時,已經將filePath給加載好了,我們看一下控制檯的啓動信息:
以上就是Spring加載properties配置文件的兩種方式。實際上,上面基於xml方式中的PropertyPlaceholderConfigurer類和這裏基於註解方式的PropertiesFactoryBean類都是繼承PropertiesLoaderSupport,都是用來加載properties配置文件的。
如有錯誤之處,歡迎留言指正~