我使用Spring XML定义我的Camel Context。是否可以在运行时在Java中获得相同的camelcontext对象?我需要此对象来添加更多数据并将其发送到现有路由。我无法用XML做到这一点,并且需要该对象,因为我将侦听错误,并且必须在触发事件侦听器时采取行动。
<?xml version="1.0" encoding="UTF-8"?>
<!-- Configures the Camel Context-->
<camelContext id="ovcOutboundCamelContext"
errorHandlerRef="deadLetterErrorHandler"
xmlns="http://camel.apache.org/schema/spring"
useMDCLogging="true">
<route id="processAuctionMessageRoute">
<from uri="direct:processAuctionMessage"/>
<to uri="bean:CustomerService?method=processAuctionMessage"/>
<to uri="direct:splitMessage"/>
</route>
<route id="splitMessagesRoute">
<from uri="direct:splitMessage"/>
<split parallelProcessing="true" executorServiceRef="auctionsSplitThreadPoolProfile" id="splitId">
<simple>${body}</simple>
<to uri="bean:CustomerService?method=transformCompanyMessageForAuction"/>
<to uri="bean:CustomerService?method=processCompanyMessageForAuction"/>
</split>
<to uri="direct:end"/>
</route>
<route id="endProcessor">
<from uri="direct:end"/>
<log loggingLevel="INFO" message="End of route ${threadName}"/>
</route>
</camelContext>
我正在尝试使用Java中已经存在的路由来获取此上下文,但是它不起作用。请帮忙。
public void test() throws Exception {
CamelContext context = new DefaultCamelContext();
context.start();
System.out.println("context:" + context.getRoutes().size());
context.getRoute("direct:gotoExistingProcess");
addRoutesToCamelContext(context);
System.out.println("context:" + context.getRoutes().size());
context.stop();
}
最佳答案
在 Camel 的文档中,我们有:
CamelContextAware
如果您想在POJO中注入CamelContext,则只需实现CamelContextAware接口即可;然后当Spring创建您的POJO时,CamelContext将被注入到您的POJO中。另请参阅Bean集成以进行进一步的注入。
您可以在Spring中创建一个实现CamelContextAware的bean,如下所示:
@Service
public class RouteManager implements CamelContextAware {
protected CamelContext camelContext;
public CamelContext getCamelContext() {
return camelContext;
}
public void setCamelContext(CamelContext camelContext) {
this.camelContext = camelContext;
}
}
如果不使用注释,则可以使用:
<bean id="RouteManager " class="myPackage.RouteManager" />
获取上下文后,您可以使用您的代码,但不必启动或停止上下文。