TcpConnectionFactoryFactoryBean不支持循环引用?

时间:2015-03-30 15:50:42

标签: java spring spring-integration

我正在尝试使用TcpInboundGateway创建一个简单的spring

但以下不起作用:

@EnableIntegration
@IntegrationComponentScan
public class MyEndpoint {
    @Bean
    public TcpInboundGateway gateway() throws Exception {
        TcpInboundGateway gate = new TcpInboundGateway();
        TcpConnectionFactoryFactoryBean fact = new TcpConnectionFactoryFactoryBean();
        fact.setType("server");
        fact.setPort(5555);
        gate.setConnectionFactory(fact.getObject());
        gate.setRequestChannel(new RendezvousChannel());
        return gate;
    }
}

结果:

Caused by: org.springframework.beans.factory.FactoryBeanNotInitializedException: org.springframework.integration.ip.config.TcpConnectionFactoryFactoryBean does not support circular references
    at org.springframework.beans.factory.config.AbstractFactoryBean.getEarlySingletonInstance(AbstractFactoryBean.java:164)
    at org.springframework.beans.factory.config.AbstractFactoryBean.getObject(AbstractFactoryBean.java:148)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
    ... 31 more

这里可能缺少什么?

2 个答案:

答案 0 :(得分:2)

将您的代码更改为

@Bean
public TcpInboundGateway gateway(AbstractConnectionFactory connectionFactory) throws Exception {
    TcpInboundGateway gate = new TcpInboundGateway();
    gate.setConnectionFactory(connectionFactory);
    gate.setRequestChannel(new RendezvousChannel());
    return gate;
}

@Bean
public TcpConnectionFactoryFactoryBean connectionFactory() {
    TcpConnectionFactoryFactoryBean fact = new TcpConnectionFactoryFactoryBean();
    fact.setType("server");
    fact.setPort(5555);
    return fact;
}

Spring有一种处理FactoryBean实例的特定方法,而gateway bean在初始化getObject之前调用TcpConnectionFactoryFactoryBean会打破它(你也可以调用{{1}初始化内联)。使用上面的代码,你让Spring负责初始化。

答案 1 :(得分:1)

您误解了一些JavaConfig概念。请阅读更多Spring Framework Manual Reference

您特定案例的答案:任何FactoryBean都必须配置为单独的@Beanmethod argument injection之类的引用:

@Bean
public TcpConnectionFactoryFactoryBean connectionFactory() {
    TcpConnectionFactoryFactoryBean fact = new TcpConnectionFactoryFactoryBean();
    fact.setType("server");
    fact.setPort(5555);
    return fact;
}

@Bean
public TcpInboundGateway gateway(AbstractConnectionFactory connectionFactory) throws Exception {
   TcpInboundGateway gate = new TcpInboundGateway();
   gate.setConnectionFactory(connectionFactory);
   gate.setRequestChannel(new RendezvousChannel());
   return gate;
}

除了RendezvousChannel作为你自己的bean之外,还有一个问题:How to create channels with Spring 4 annotation based?