由于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。
谁知道我该怎么做?
谢谢!
由于您在中使用了@Publisher注释ExampleService,因此可以将其作为发布内容的代理。
@Publisher
ExampleService
解决该问题的唯一方法是为您公开一个接口,并将该接口ExampleService已经注入到您的测试类中:
public interface ExampleServiceInterface { String sendMessage(String message); } ... public class ExampleService implements ExampleServiceInterface { ... @Autowired private ExampleServiceInterface exampleService;
另一方面,您ExampleService.sendMessage()似乎对消息不执行任何操作,因此您可以考虑@MessagingGateway在某个界面上使用a :https://docs.spring.io/spring- integration/reference/html/messaging-endpoints-chapter。 html#gateway
ExampleService.sendMessage()
@MessagingGateway