2010-01-14 76 views
3

我在這裏遇到的基本問題是我有一個xml文件被用作實用程序文件並導入到其他xml文件中。它定義了一系列連接到平臺並提供接口的對象。這個文件中的bean被定義爲延遲初始化的,所以如果你不想連接到平臺,你將不會,但如果你開始引用適當的bean,那麼一切都應該起來並運行。在Spring中聲明一個顯式對象依賴關係

我遇到的基本問題是這個集合中的一個bean沒有被任何其他bean引用,但它需要被構造,因爲它會調用其他bean的方法來「激活「它。 (它根據它檢測到的平臺狀態,通過打開/關閉連接來充當門禁人員)。

這裏的排序XML設置的我有一個虛擬的:

<?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:util="http://www.springframework.org/schema/util" 
    xsi:schemaLocation=" 
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd 
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd" 
    default-lazy-init="true"> 

    <!-- Provides the connection to the platform --> 
    <bean id="PlatformConnection"> 
     <constructor-arg ref="PlatformConnectionProperties" /> 
    </bean> 

    <!-- This bean would be overriden in file importing this XML --> 
    <bean id="PlatformConnectionProperties"/> 

    <!-- Controls the databus to be on/off by listening to status on the Platform 
     (disconnections/reconnections etc...) --> 
    <bean lazy-init="false" class="PlatformStatusNotifier"> 
     <constructor-arg ref="PlatformConnection" /> 
     <constructor-arg ref="PlatformConnectionDataBus" /> 
    </bean> 

    <!-- A non platform specific databus for client code to drop objects into - 
     this is the thing that client XML would reference in order to send objects out --> 
    <bean id="PlatformConnectionDataBus" class="DataBus"/> 

    <!-- Connects the DataBus to the Platform using the specific adaptor to manage the java object conversion --> 
    <bean lazy-init="false" class="DataBusConnector"> 
     <constructor-arg> 
      <bean class="PlatformSpecificDataBusObjectSender"> 
       <constructor-arg ref="PlatformConnection" /> 
      </bean> 
     </constructor-arg> 
     <constructor-arg ref="PlatformConnectionDataBus" /> 
    </bean> 

</beans> 

現在基本上我想刪除的那些需要得到這個東西才能正常工作懶惰inits這裏。客戶端XML引用的對象是PlatformConnectionPlatformConnectionDataBus。我如何明確地聲明,如果它們被引用,我希望構建其他bean?

回答

5

您可以從一個豆使用depends-on添加屬性的顯式依賴另一個:

<bean id="a" class="A"/> 
<bean id="b" class="B" depends-on="a"/> 

如果我正確理解你的questin,那麼我建議你讓所有的bean定義lazy-init="true",並使用depends-on綁在一起,例如:

<bean id="PlatformStatusNotifier" lazy-init="false" class="PlatformStatusNotifier"> 
    <constructor-arg ref="PlatformConnection" /> 
    <constructor-arg ref="PlatformConnectionDataBus" /> 
</bean> 

<bean id="PlatformConnectionDataBus" lazy-init="false" class="DataBus" depends-on="PlatformStatusNotifier"/> 

所以,如果您的客戶端配置爲表達對PlatformConnectionDataBus的依賴,那麼這將觸發初始化,這又會觸發PlatformStatusNotifier的初始化。