我需要使用服务激活器。我想在运行时而不是在开发或部署时将其绑定到输入和输出通道。因此,不能使用基于 XML 的服务激活器实例化。我在程序执行期间声明交换和队列。因此,需要在程序执行期间动态实例化服务激活器。
我想实现以下目标,但使用代码而不是 XML:
<service-activator input-channel="exampleChannel" output-channel="replyChannel"
ref="somePojo" method="someMethod"/>
上述 XML 代码段的等效代码是什么?似乎在 Spring-Integration 中没有 ServiceActivator 类。
谢谢。
这个问题已经回答了,但我认为一个例子可能会很好。
public class NoContextExample {
private static final Logger logger = Logger.getLogger(NoContextExample.class);
public static void main(String[] args) {
//register an input channel
SubscribableChannel inputChannel = new DirectChannel();
//register a service-activator message handler
ServiceActivatingHandler serviceActivator = new ServiceActivatingHandler(new somePojo(),"someMethod");
//set service activator as a handler for input channel
inputChannel.subscribe(serviceActivator);
//register an output channel
SubscribableChannel outputChannel = new DirectChannel();
//set the service activator's output channel to outputChannel
serviceActivator.setOutputChannel(outputChannel);
//register a message handler for output channel
MessageHandler handler = new MessageHandler(){
@Override
public void handleMessage(Message<?> message) throws MessagingException{
logger.info("MessageChannel.handleMessage ["+message.getPayload()+"]");
}
};
//subscribe message handler to output channel
//this is equivalent to EventDrivenConsumer consumer = new EventDrivenConsumer(outputChannel, handler);
//and then doing consumer.start(); then inputChannel.send(); then consumer.stop();
outputChannel.subscribe(handler);
// we are now ready to send the message on input channel
inputChannel.send(new GenericMessage<String>("World"));
}
}
有一个类适合你 - ServiceActivatingHandler
.但是在运行时做到这一点并不容易。当然,您可以简单地向该类的构造函数提供您的 POJO 及其方法。进一步和重要的选择是outputChannel
。在这里,您应该以某种方式提供BeanFactory
基础设施:beanFactory
,beanClassLoader
属性等。称其afterPropertiesSet()
.主要目标 - 将该处理程序订阅到exampleChannel
.这取决于该通道的类型。如果是直接的或执行者,则足以构建EventDrivenConsumer
.但是如果它排队,你应该建立PollingConsumer
.
这只是如何完成任务的草稿,可能还有其他东西需要为复杂的解决方案构建。