2013-03-22 83 views
0

我是Spring的新手,我遇到了需要幫助的場景。 我的情景是我有一個像這樣的特定模塊的bean定義。Spring動態注入一個屬性

<bean name="ruleEngineAction" class="com.xxxxx.yyyy.UserAction" scope="prototype"> 
<property name="userManager"> 
    <ref bean="userManager" /> 
</property> 
<property name="userDto"> 
     <ref bean="userDto" /> 
</property> 
</bean> 

現在這個bean中我想用一個更財產,但與在bean定義取決於像

<property name="roleManager"> 
    <ref bean="roleManager"> 
</property> 

應用流量,使我應該包括該物業本身或我能做到這一點動態地在代碼中,因爲我不希望這個屬性被大量使用。

請給我建議正確和有效的方法。

+2

您可以通過將bean作爲ApplicationContext.getBean(「bean name」)來獲取bean的代碼。..我不知道這是不是你想要的 – Anubhab 2013-03-22 06:57:53

回答

2

從我所瞭解的問題來看,只有一個roleManager類型的豆,但是roleManager的用法是基於應用程序流。

在這種情況下,我會建議您將roleManager注入ruleEngineAction,就像您對任何其他bean所做的一樣,但僅在需要時才使用該bean。

在正常的類中添加不必要的依賴項是一種不好的做法,例如添加對在運行時動態獲取bean的引用的applicationContext

0

那麼你需要在你的com.xxxxx.yyyy.UserAction類添加與getter和setter新屬性roleManager,如:

class UserAction { 
    // your previous properties userManager, userDto, etc. 

    private RoleManager roleManager; // assuming interface/class as RoleManager for roleManager 

    // getter and setter for roleManager 

    // your other action methods which will use roleManager 

} 
1

不管是不是,你注入這個bean,它會反正被Spring創建。爲什麼不把房產納入你的UserAction以及是否使用它,可以在你的班級中決定。注入bean沒有什麼壞處,因爲你會在某些場景中使用它。

如果情況是這樣的,對象不會被創建,如果你不注入/使用,那麼考慮這種情況是有道理的,但是由於Spring會反過來創建對象,注入它是一個問題。

0

如果你注入也沒有問題。只要你訪問該類,它就會創建該類的對象。

相關問題