Spring Cloud Stream and @Publisher annotation compatiblity

我是研究僧i 提交于 2019-12-20 02:40:09

问题


Since Spring Cloud Stream has not an annotation for sending a new message to a stream (@SendTo only works when @StreamListener is declared), I tried to use Spring Integration annotation for that purpose, that is @Publisher.

Because @Publisher takes a channel and @EnableBinding annotations of Spring Cloud Stream can bind an output channel using @Output annotation, I tried to mix them in the following way:

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

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

Also, I declared @EnablePublisher annotation in a configuration file:

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

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

My test:

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

    @Autowired
    private ExampleService exampleService;

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

But I'm getting the following error:

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'

Problem here is that ExampleService bean can not be injected.

Anyone knows how can I make this work?

Thanks!


回答1:


Since you use a @Publisher annotation in your ExampleService, it is proxied for that publishing stuff.

Only the way to overcome the issue is to expose an interface for your ExampleService and inject already that one into your test class:

public interface ExampleServiceInterface {

     String sendMessage(String message);

}

...

public class ExampleService implements ExampleServiceInterface {

...


@Autowired
private ExampleServiceInterface exampleService;

On the other hand it looks like your ExampleService.sendMessage() does nothing with the message, so you may consider to use a @MessagingGateway on some interface instead: https://docs.spring.io/spring-integration/reference/html/messaging-endpoints-chapter.html#gateway



来源:https://stackoverflow.com/questions/54150939/spring-cloud-stream-and-publisher-annotation-compatiblity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!