2011-10-19 123 views
0

當在Spring ApplicationContext中使用屬性文件時,可以通過以下方式訪問其屬性:$ {someproperty}在xml配置文件中。但是,如何在不通過xml注入的情況下訪問java代碼中的相同屬性?如何通過ApplicationContext訪問屬性

的ApplicationContext配置

<?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"> 
    <bean id="placeholderConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
     <property name="location" value="myapp.properties" /> 
    </bean> 
    <bean class="my.app.MyClass"> 
     <property name="foo" value="${someproperty}" /> 
    </bean> 
</beans>

屬性

someproperty=somevalue

更新1
這樣做的實際點,就是對應用程序的唯一ID是一個特例在屬性文件中設置(由系統管理員編輯)。有幾個應用程序類實現了ApplicationContextAware,因此它們可以訪問上下文並防止在每個類中注入或爲每個我們想要一個ez屬性訪問方法的類定義一個bean。我們的應用程序「瞭解」Spring在這種情況下不是問題。

+0

你能解釋一下「防止在每個班級注射或爲每個班級定義一個bean」嗎? – kan

+0

如果我們不使用註釋,那麼對於每個需要訪問屬性本身的bean,都應該使用「property」標籤。它只是將工作從類移動到xml。 –

+0

我實際上傾向於使用類似於此博客文章中的配置類:http://chrislovecnm.com/2010/03/08/spring-3-java-based-configuration-with-value/ –

回答

3

它沒有任何意義訪問屬性它違背了IoC原則,這是Spring的主要目標。除了其他答案,可能你需要所有的屬性?在這種情況下,有一個PropertiesFactoryBean對象,它可以讓你Properties對象有權訪問所有屬性。

PropertyPlaceholderConfigurer bean旨在在春季環境中替換佔位符。至少任何其他用法都是令人困惑的。

0

我會(在ApplicationContext中或通過注射它EG)獲取placeHolderConfig bean時,PropertyPlaceholderConfigurer有這種訪問方法,看看這裏:

http://static.springsource.org/spring/docs/2.0.x/api/org/springframework/beans/factory/config/PropertyResourceConfigurer.html#convertPropertyValue(java.lang.String

+1

這不是一種「訪問方法」。這是一種延伸保護可見性的內部方法 - 絕對不能以這種方式使用。 –

+0

你是對的,還沒有看到受保護的修飾符:( – HefferWolf

1

良好的風格有你的代碼儘可能少地瞭解Spring,但可以通過注入屬性或構造函數(取決於如何構建bean)的註釋(假設您使用Spring 3)來注入它。否則,你可以選擇它的Web應用程序的配置,但根據我的經驗,這是更容易出錯。 (關於使用Spring做的另一個好處是它可以很容易地將來自多個不同來源的屬性與複雜的替代規則合併在一起,手動操作是很痛苦的。)

+0

這看起來很有前途,是的,我們正在使用Spring 3 –