1,有些參數(shù)在某些階段中是常量。
在開發(fā)階段我們連接數(shù)據(jù)庫時(shí)的url,username,password等信息
分布式應(yīng)用中client端的server地址,端口等
2,這些參數(shù)在不同階段之間又住住需要改變
期望:有一種方案可以方便我們在一個(gè)階段內(nèi)不需要頻繁寫一個(gè)參數(shù)的值,而在不同階段間又可以方便的切換參數(shù)的配置信息
解決:spring3中提供了一種簡便的方式就是 content:property-placeholder元素
只需要在spring配置文件中添加一句:
<context:property-placeholder location="classpath:jdbc.properties"/>
1
或者
<bean id="propertyPlaceholderConfigurer" class="org.springframework,beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>jdbc.properties<value/>
</list>
</property>
</bean>
1
2
3
4
5
6
7
即可,這里的location值為參數(shù)配置文件的位置,配置文件通常放到src目錄下,參數(shù)配置文件的格式即鍵值對的形式,
jdbc配置
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test
username=root
password=root
1
2
3
4
5
行內(nèi)#號后面部分為注釋
這樣一來就可以為spring配置的bean的屬性設(shè)置值了,比如spring有一個(gè)數(shù)據(jù)源的類
<bean id="dataSource" class="org.springframework,jdbc,datasource.DriverManagerDataSource">
<property name="driverClassName" value="${driverClassName}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</bean>
1
2
3
4
5
6
甚至可以將 ${} 這種形式的變量用在spring提供的注解當(dāng)中,為注解的屬性提供值(下面會講到)
Spring容器采用反射掃描的發(fā)現(xiàn)機(jī)制,在探測到Spring容器中有一個(gè) org.springframework.beans.config.PropertyPlaceholderConfigurer的Bean就會停止對剩余PropertyPlaceholderConfigurer的掃描,
換句話說,即Spring容器僅允許最多定義一個(gè)PropertyPlaceholderConfigurer 或 content:property-placeholder其余的會被Spring忽略
由于Spring容器只能有一個(gè)PropertyPlaceholderConfigurer,如果有多個(gè)屬性文件,這時(shí)就看誰先誰后了,先的保留 ,后的忽略。
還有一種情況,是Spring 自動注入 properties文件中的配置:要自動注入properties文件中的配置,需要在Spring配置文件中添加 org.springframework.beans.factory.config.PropertiesFactoryBean和org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer的實(shí)例配置
<bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value> classpath*:application.properties</value>
</list>
</property>
</bean>
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
<property name="properties" ref="configProperties" />
</bean>
1
2
3
4
5
6
7
8
9
10
在這個(gè)配置文件中我們配置了注解掃描,和configProperties實(shí)例和propertyConfigurer實(shí)例,這樣我們就可以在java類中自動注入配置了
@Component
public class Test{
@Value("#{configProperties['userName']}")
private String userName;
public String getUserName(){
return userName;
}
}
1
2
3
4
5
6
7
8
9
10
自動注入需要使用 @Value 這個(gè)注解,這個(gè)注解的格式 #{configProperties['userName']}其中configProperties是我們在配置文件中配置的bean的 id, userName 是在配置文件中配置的項(xiàng)