Spring Cloud Stream和@Publisher注释兼容性

时间:2019-01-11 16:57:22

标签: spring spring-boot spring-integration spring-cloud spring-cloud-stream

由于Spring Cloud Stream没有用于向流发送新消息的注释(@SendTo仅在声明@StreamListener时有效),因此我尝试为此目的使用Spring Integration注释,即@Publisher。

由于@Publisher需要一个频道,并且Spring Cloud Stream的@EnableBinding批注可以使用@Output批注绑定输出频道,因此我尝试通过以下方式进行混合:

@EnableBinding(MessageSource.class)
@Service
public class ExampleService {

    @Publisher(channel = MessageSource.OUTPUT)
    public String sendMessage(String message){
        return message;
    }
}

此外,我在配置文件中声明了@EnablePublisher批注:

@SpringBootApplication
@EnablePublisher("")
public class ExampleApplication {

    public static void main(String[] args){
        SpringApplication.run(ExampleApplication.class, args);
    }
}

我的测试:

@RunWith(SpringRunner.class)
@SpringBootTest
public class ExampleServiceTest {

    @Autowired
    private ExampleService exampleService;

    @Test
    public void testQueue(){
        exampleService.queue("Hi!");
        System.out.println("Ready!");
    }
}

但是我遇到以下错误:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.example.ExampleServiceTest': Unsatisfied dependency expressed through field 'exampleService'; nested exception is 
org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'exampleService' is expected to be of type 'com.example.ExampleService' but was actually of type 'com.sun.proxy.$Proxy86'

这里的问题是不能注入ExampleService bean。

任何人都知道我该如何进行这项工作?

谢谢!

2 个答案:

答案 0 :(得分:2)

由于您在@Publisher中使用了ExampleService批注,因此该批注将被代理。

解决该问题的唯一方法是公开ExampleService的接口,并将该接口注入您的测试类:

public interface ExampleServiceInterface {

     String sendMessage(String message);

}

...

public class ExampleService implements ExampleServiceInterface {

...


@Autowired
private ExampleServiceInterface exampleService;

另一方面,您的ExampleService.sendMessage()似乎对消息没有任何作用,因此您可以考虑在某个界面上使用@MessagingGatewayhttps://docs.spring.io/spring-integration/reference/html/messaging-endpoints-chapter.html#gateway

答案 1 :(得分:1)

为什么不像下面那样手动将消息发送到流中。

@Component
@Configuration
@EnableBinding(Processor.class)
public class Sender {

    @Autowired
    private Processor processor;

    public void send(String message) {

        processor.output().send(MessageBuilder.withPayload(message).build());

    }

}

您可以通过测试仪对其进行测试。

@SpringBootTest
public class SenderTest {

    @Autowired
    private MessageCollector messageCollector;

    @Autowired
    private Processor processor;

    @Autowired
    private Sender sender;

    @SuppressWarnings("unchecked")
    @Test
    public void testSend() throws Exception{

        sender.send("Hi!");
        Message<String> message = (Message<String>) this.messageCollector.forChannel(this.processor.output()).poll(1, TimeUnit.SECONDS);
        String messageData = message.getPayload().toString();
        System.out.println(messageData);

    }

}

您应该看到“嗨!”在控制台中。