2

我有一些代码,其中属性仅在运行时知道。

在这种情况下,用户可以输入 URL 以及用户名和密码。

ConnectionFactory cf = (ConnectionFactory) this.factory.getBean(
            "topicConnectionFactory", <URL which is entered at runtime>)
final UserCredentialsConnectionFactoryAdapter connectionFactory = this.factory
            .getBean(UserCredentialsConnectionFactoryAdapter.class);

    connectionFactory.setTargetConnectionFactory(cf);

UserCredentialsConnectionFactoryAdapter没有构造函数基础设置,因此唯一的方法是使用无参数构造函数创建并在之后设置属性,但是 spring 运行 InitializingBean 会引发未设置 TargetConnectionFactory 的错误

有没有办法在弹簧创建期间传递此信息或弹簧延迟 Bean 的初始化。

为了理解范围,下面是 spring 的配置部分。

<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate"
    scope="prototype" />


<bean id="userCredentialsConnectionFactory"     class="org.springframework.jms.connection.UserCredentialsConnectionFactoryAdapter"
    scope="prototype" >
</bean>

<bean id="cachingFactory"
    class="org.springframework.jms.connection.CachingConnectionFactory"
    scope="prototype" />

<bean id="tibcoTopicConnectionFactory" class="com.tibco.tibjms.TibjmsTopicConnectionFactory"
    scope="prototype" />

如前所述,url、用户名和密码直到运行时才知道并且可以更改。该应用程序是多线程的。想法是连接到某个地方,发送消息,断开连接

4

1 回答 1

1

您可以执行以下操作:

编写自己的UserCredentialsConnectionFactoryAdapterConnectionFactory用作构造函数参数的扩展:

public class CustomUserCredentialsConnectionFactoryAdapter extends UserCredentialsConnectionFactoryAdapter {

    public CustomUserCredentialsConnectionFactoryAdapter(ConnectionFactory target){
        super();
        setTargetConnectionFactory(target);
    }

}

然后像这样使用它:

ConnectionFactory cf = (ConnectionFactory) this.factory.getBean(
        "topicConnectionFactory", <URL which is entered at runtime>)
final UserCredentialsConnectionFactoryAdapter connectionFactory = this.factory
        .getBean("userCredentialsConnectionFactory", cf);

不要忘记更改您的 bean 声明:

      <bean id="userCredentialsConnectionFactory"
       class="com.company.CustomUserCredentialsConnectionFactoryAdapter"
scope="prototype" >
    </bean>
于 2013-02-14T12:27:10.583 回答