在Spring中声明显式对象依赖项

时间:2010-01-14 07:42:49

标签: java spring

我在这里遇到的基本问题是我有一个xml文件被用作实用程序文件并导入到其他xml文件中。它定义了一系列对象,用于连接到平台并为其提供接口。此文件中的bean被定义为延迟初始化,因此如果您不想连接到平台,则不会,但如果您开始引用相应的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>

现在基本上我想删除这里需要使这个东西正常工作的懒惰。客户端XML引用的对象是PlatformConnectionPlatformConnectionDataBus。如果引用它们,我怎么能明确声明我想要构造其他bean呢?

1 个答案:

答案 0 :(得分:5)

您可以使用depends-on属性将一个bean的显式依赖项添加到另一个bean:

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

如果我正确理解您的任务,那么我建议您制作所有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的依赖,则会触发PlatformConnectionDataBus的初始化,这反过来会触发PlatformStatusNotifier的初始化。

相关问题