2016-10-17 15 views
3

在Spring框架中使用PropertyOverrideConfigurerPropertyPlaceholderConfigurer有什麼區別?我無法找到這兩個類之間的任何固體差異。PropertyOverrideConfigurer和PropertyPlaceholderConfigurer有什麼區別?

+1

這是[您所選擇的搜索引擎]完美的問題,而是完全偏離主題爲SO。 –

+1

Franz Gleichmann爲什麼是這個問題? – Siddharth

+1

雖然我不同意這是不重要的,但他確實有一個要點,即「PropertyOverrideConfigurer PropertyPlaceholderConfigurer」指向「PropertyOverrideConfigurer」的API文檔,它包含一段關於這兩者之間差異的段落。 – g00glen00b

回答

4

PropertyOverrideConfigurer:

「它覆蓋在 應用程序上下文定義bean的屬性值屬性的資源配置者它推動從屬性值 文件到bean定義。」

它允許您覆蓋某些值豆類走,意味着你可以在屬性文件中定義的屬性覆蓋春大豆的一些值

聲明:

<bean class="org.springframework.beans.factory.config.PropertyOverrideConfigurer"> 
    <property name="location" value="classpath:myproperties.properties" /> 
</bean> 

<bean id="person" class="com.sample.Employee" > 
     <property name="name" value="Dugan"/> 
     <property name="age" value="50"/>  
</bean> 

myproperties.properties :

person.age=40 
person.name=Stanis 

所以當你載入bean

Employee e = (Employee)context.getBean(Employee.class); 

e.getAge() => 40 
e.getName() => "Stanis" 

PropertyPlaceholderConfigurer

解決$ {...}針對本地性和/或系統 屬性和環境變量的佔位符。

它允許您在bean定義中解析$ {..}佔位符,它還檢查系統屬性的值。這種行爲可以通過systemPropertiesMode

  • 無法控制(0):從不檢查系統屬性
  • 回退(1):檢查系統屬性,如果在指定的 屬性文件無法解析。這是默認設置。
  • 覆蓋(2):先檢查系統屬性,然後再嘗試 指定的屬性文件。這使得系統屬性可以覆蓋任何其他屬性來源 。

配置

<bean id="dataSource" 
     class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 

     <property name="driverClassName" value="com.mysql.jdbc.Driver" /> 
     <property name="url" value="jdbc:mysql://localhost:3306/mydb" /> 
     <property name="username" value="root" /> 
     <property name="password" value="password" /> 
     <property name="systemPropertiesMode" value="0" /> 
    </bean> 

移動 '數據源' 屬性的屬性文件

數據庫。性能

jdbc.driverClassName=com.mysql.jdbc.Driver 
jdbc.url=jdbc:mysql://localhost:3306/mydb 
jdbc.username=root 
jdbc.password=password 



<bean 
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 

    <property name="location"> 
     <value>database.properties</value> 
    </property> 
</bean> 

然後用佔位符是指他們=>

<bean id="dataSource" 
     class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 

     <property name="driverClassName" value="${jdbc.driverClassName}" /> 
     <property name="url" value="${jdbc.url}" /> 
     <property name="username" value="${jdbc.username}" /> 
     <property name="password" value="${jdbc.password}" /> 
    </bean> 
+0

謝謝kuhajeyan – Siddharth