Spring并将Bean Init延迟到属性设置后

时间:2013-02-14 11:15:30

标签: java spring

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

在这种情况下,用户可以输入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 没有构造函数基础设置,因此唯一的方法是使用no-arg构造函数创建并在之后设置属性,但是spring运行InitializingBean,抛出TargetConnectionFactory的错误没有设定。

有没有办法在Spring创建过程中传递这些信息,或者春天延迟Bean的初始化。

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

<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,用户名和密码在运行时才知道并且可以更改。该应用程序是多线程的。想法是连接到某个地方,发送消息,断开连接

1 个答案:

答案 0 :(得分:1)

您可以执行以下操作:

使用UserCredentialsConnectionFactoryAdapter作为构造函数参数编写自己的ConnectionFactory扩展名:

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 decaration:

      <bean id="userCredentialsConnectionFactory"
       class="com.company.CustomUserCredentialsConnectionFactoryAdapter"
scope="prototype" >
    </bean>