spring的配置文件相對是固定的,一般做爲資源文件存在,而程序中常常會有一些須要配置的變量,好比數據庫的鏈接信息,memcached的地址信息等等,這些信息最好單獨放在java的配置文件properties文件中。java
下面咱們經過一個例子演示如何在spring中使用properties文件中的配置。spring
首先新建一個maven項目,並在依賴中添加spring相關的項,若是不知道添加那些依賴,請參照上一篇文章。數據庫
建好項目以後,咱們新建一個java的接口IDog,和這個接口的兩個實現類CommonDog和BeautifulDog。IDog有兩個方法getWeight()和run()方法:數組
package cn.outofmemory.hellospring.properties;public interface IDog { void run(); int getWeight();}
CommonDog和BeatifulDog的實現以下:app
package cn.outofmemory.hellospring.properties;public class CommonDog implements IDog { private int weight; public void setWeight(int weight) { this.weight = weight; } public int getWeight() { return this.weight; } @Override public void run() { System.out.println("common dog running..."); }}
package cn.outofmemory.hellospring.properties;public class BeautifulDog extends CommonDog implements IDog { @Override public void run() { System.out.println("running beautifully"); }}
咱們須要在spring.xml中配置App.java中要使用的IDog的實現類,和這個實現類的實例的weight值,咱們先看下spring配置文件的內容:maven
<?xml version="1.0" encoding="utf-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd "> <!-- define envirement varibles --> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" id="pphc"> <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" /> <property name="ignoreResourceNotFound" value="true" /> <property name="locations"> <list> <!-- standard config --> <value>classpath*:application.properties</value> </list> </property> </bean> <bean id="appDog" class="${dog.type}"> <property name="weight" value="${dog.weight}"/> </bean> </beans>
在這個配置文件中,咱們首先定義了類型爲org.springframework.beans.factory.config.PropertyPlaceholderConfigurer
的bean,這個bean用來將解析properties文件,spring能夠使用此類,來將其餘bean中相似EL表達式${abc}的值替換爲配置文件的值。PropertyPlaceholderConfigurer
類的locations屬性是一個數組,也就是說能夠指定多個配置文件。ide
spring.xml中的第二個bean,其id爲appDog,而其具體的類型是${dog.type}是一個配置文件的項,他的weight屬性的值是${dog.weight}也是一個配置項。memcached
咱們再看下配置文件application.properties的內容:this
dog.weight=10dog.type=cn.outofmemory.hellospring.properties.BeautifulDog
最後咱們看下以上配置是否能夠正常的工做,在App.java類中添加以下代碼:spa
package cn.outofmemory.hellospring.properties;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;/** * Hello world! * */public class App { public static void main( String[] args ) { ApplicationContext appContext = new ClassPathXmlApplicationContext("spring.xml"); IDog appDog = (IDog)appContext.getBean("appDog"); appDog.run(); String weightMsg = String.format("appDog's weight is %d", appDog.getWeight()); System.out.println(weightMsg); }}
運行程序,便可看到輸出。