在Spring中声明一个explict对象依赖项

cyb*_*org 3 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>
Run Code Online (Sandbox Code Playgroud)

现在基本上我想删除这里所需的懒惰,以使这个东西正常工作.客户端XML引用的对象是PlatformConnectionPlatformConnectionDataBus.我如何明确地声明我想要引用那些其他bean?

ska*_*man 5

您可以使用以下depends-on属性从一个bean向另一个bean添加显式依赖项:

<bean id="a" class="A"/>
<bean id="b" class="B" depends-on="a"/>
Run Code Online (Sandbox Code Playgroud)

如果我正确理解你的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"/>
Run Code Online (Sandbox Code Playgroud)

因此,如果您的客户端配置表示依赖PlatformConnectionDataBus,那么这将触发初始化PlatformConnectionDataBus,这反过来将触发初始化PlatformStatusNotifier.