2009-04-28 117 views
6

如何在運行時使用java彈簧動態更改bean的屬性? 我有一個bean mainView,應該使用屬性「class」「class1」或「class2」。 這個決定應該基於屬性文件進行,其中屬性「withSmartcard」爲「Y」或「N」。動態更改彈簧豆

的ApplicationContext:

<bean id="mainView" 
    class="mainView"> 
    <property name="angebotsClient" ref="angebotsClient" /> 
    <property name="class" ref="class1" /> 
</bean> 



<bean id="class1" 
    class="class1"> 
    <constructor-arg ref="mainView" /> 
</bean> 

<bean id="class2" 
    class="class2"> 
    <constructor-arg ref="mainView" /> 
</bean> 

PropertyFile:

withSmartcard = Y

回答

1

使用類工廠。 它可以基於你的財產返回實例。

10

使用PropertyPlaceHolder來管理您的屬性文件..

<bean id="myPropertyPlaceHolder" 
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
    <description>The service properties file</description> 
    <property name="location" value="classpath:/some.where.MyApp.properties" /> 
    </bean> 

,改變你的ref屬性如下:

<bean id="mainView" 
    class="mainView"> 
    <property name="angebotsClient" ref="angebotsClient" /> 
    <property name="class" ref="${withSmartCardClassImplementation}" /> 
</bean> 

在你的屬性文件some.where.MyApp.properties,加鍵名爲withSmartCardClassImplementation,它將具有class1或class2(您選擇)作爲值。

withSmartCardClassImplementation=class1 
+0

它應該是{$ classIdToBeUsed}還是$ {classIdToBeUsed}? – 2009-04-28 13:35:30

+0

$ {classIdToBeUsed} :)錯字,謝謝!顯然,我改變classIdToBeUsed forSmartCardClassImplementation – Olivier 2009-04-28 13:39:28

4

您想要PropertyPlaceholderConfigurer。該手冊的這一部分比我現場可以更好地展示它。

在您的示例中,您需要將屬性的值更改爲class1class2(春季上下文中所需bean的名稱)。

或者,你的配置可能是:

<bean id="mainView" 
    class="mainView"> 
    <property name="angebotsClient" ref="angebotsClient" /> 
    <property name="class"> 
     <bean class="${classToUse}"> 
      <constructor-arg ref="mainView"/> 
     </bean> 
    </property> 
</bean> 

與包含配置文件: classToUse = fully.qualified.name.of.some.Class

使用Bean或類名也不會在用戶可編輯的配置文件中可以接受,而且您確實需要使用「Y」和「N」作爲配置參數值。在這種情況下,你只需要用Java來做到這一點,Spring並不打算完成。

MAINVIEW可以訪問直接應用程序上下文:

if (this.withSmartCards) { 
    this.class_ = context.getBean("class1"); 
} else { 
    this.class_ = context.getBean("class2"); 
} 

一個清潔的解決方案是在它自己的類被包封用戶配置的處理,將執行上述操作,以減少需要被了ApplicationContextAware類的數量並根據需要將其注入到其他課程中。

使用BeanFactoryPostProcessor,您可以以編程方式註冊類屬性的定義。使用FactoryBean,您可以動態創建一個bean。兩者都是Spring的一些先進用法。

另一方面:我不確定您的示例配置是否合法,因爲mainView和class1/class2之間存在循環依賴關係。

1

同意上面的@Olivier。

有很多方法可以做到這一點。

  1. 使用PropertyPlaceHolderConfigurer ..
  2. 使用的BeanPostProcessor ..
  3. 使用Spring AOP中,創建一個意見和操縱性能。

我會推薦以上的產品編號:1。