【问题标题】:How to Autowire Binding interfaces?如何自动装配绑定接口?
【发布时间】:2019-03-02 14:39:15
【问题描述】:

基于本期对话#1623Binder ImplementationSpring Cloud Stream Refrence

我想注入 Sink 对象,并订阅一个 MessageHandler 到输入通道,但是调用 Annotated ApplicationConfig 时似乎没有正确创建对象。

 @Configuration
public class ApplicationConfig {

    @Autowired
    public void configureInboundEventMessageChannelAdapter(EventBus eventBus,Sink sink) {
        System.out.println("sink :" + sink.toString());
        System.out.println("sink input :" + sink.input().toString());
        System.out.println("Bus :" + eventBus.toString());
        InboundEventMessageChannelAdapter inboundEventMessageChannelAdapter = new InboundEventMessageChannelAdapter(eventBus);
        sink.input().subscribe(inboundEventMessageChannelAdapter);
    }

InboundEventMessageChannelAdapter 是上述代码中的MessageHandler

输出:

sink :null
sink input :org.springframework.cloud.stream.messaging.DirectWithAttributesChannel@32940ff0
Bus :org.axonframework.eventhandling.SimpleEventBus@707a6ff6
2019-03-02 16:51:05.915  INFO 21 --- [           main] o.s.c.s.m.DirectWithAttributesChannel    : Channel 'unknown.channel.name' has 1 subscriber(s).

【问题讨论】:

  • 你是自动连接 Source,而不是 Sink。
  • 嗨。这是来自 Spring Cloud Stream 文档的示例代码。
  • 但是你的语言没有意义I want to inject Sink instance,and subscribe a MessageHandler to SubscribableChannel from Sink instance(sink.input()@Autowire private Source source - 展示你的完整申请。
  • 我真的很想知道,当创建 Binding 的整个概念以确保订阅是自动且透明地完成时,为什么会有人想要手动订阅 Binding(与此相关的任何绑定)最终用户。
  • 我编辑了这个问题。希望你明白我的意思。谢谢。

标签: spring spring-cloud-stream


【解决方案1】:

最好的绑定方式是构造方法。 自动装配注释有时会将 Object 实例化为 null。 使用构造函数依赖注入可以使属性成为最终的,所以总是有一个值。

public SomeClass class {

    private final Source source;

    @Autowired
    public SomeClass (Source source){
        this.source = source;
    }
    public void sayHello(String name){
        source
            .output()
           .send(MessageBuilder.withPayload(name).build());
    }
}

【讨论】:

  • 嗨。这里的自动装配方法(properties,setters,constructor) 并不重要。Sink 对象上的toString() 方法返回 null 并且输入通道在 Annotated(@Configuration) 配置中填充了未知通道名称类。
猜你喜欢
  • 2023-03-16
  • 1970-01-01
  • 1970-01-01
  • 2015-07-17
  • 2011-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多