PropertiesFactoryBean PropertyPlaceholderConfigurer 區別


 

正如 stackoverflow 上說的,PropertiesFactoryBean 是PropertiesLoaderSupport 直接的實現類, 專門用來管理properties文件的工廠bean,默認是單例的,

而 PropertyPlaceholderConfigurer 是 解決 properties 文件占位符問題的,也實現了 PropertiesLoaderSupport 類。  

 

在java 代碼里,一般是使用@Value注解來引用 properties 文件的屬性。

 

 

使用 PropertyPlaceholderConfigurer 時, @Value表達式的用法是 @Value(value="${properties key}") ,

使用 PropertiesFactoryBean 時,我們還可以用@Value 讀取 properties對象的值, @Value 用法 是 @Value(value="#{configProperties['properties key']}")

 

    <bean id="configProperties"
        class="org.springframework.beans.factory.config.PropertiesFactoryBean">
        
        <property name="locations">
            <list>
                <value>classpath:/config/jdbc.properties</value>
                <value>classpath:/config/base.properties</value>
            </list>
        </property>
    </bean>
    
    <!-- 屬性文件讀入 -->
    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="properties" ref="configProperties" />
    </bean>

 

@Value(value="${profit.rate.csProfitRate}")
double rate = 0.9;
    
@Value(value="#{configProperties['profit.rate.csProfitRate']}")
double rate2 = 0.9;

 

最后 rate 和rate2 值是一樣的。

 

 

 

參考資料:

  1、 http://stackoverflow.com/questions/20353999/propertiesfactorybean-vs-propertyplaceholderconfigurer-spring

  2、 使用spring注解方法讀取properties文件中值

  3、Spring的@PropertySource和@Value注解例子

  4、 http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-external-config-typesafe-configuration-properties

  5 、 http://outofmemory.cn/code-snippet/3700/spring-bean-property-inject 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM