apache camel documentation描述了如何使用@Component和SpringRouteBuilder注册路由构建器,然后跳转到xml代码来做
<camelContext xmlns="http://camel.apache.org/schema/spring">
<!-- and then let Camel use those @Component scanned route builders -->
<contextScan/>
</camelContext>
我怎么能用java配置做同样的事情?我有
package x.y.camel;
@Component
public class MyRouteBuilder extends SpringRouteBuilder {...}
和
@EnableWebMvc
@EnableAutoConfiguration
@ComponentScan(basePackages = {"x.y"})
public class Application implements WebApplicationInitializer {
@Bean
public SpringCamelContext camelContext(ApplicationContext applicationContext) throws Exception {
SpringCamelContext camelContext = new SpringCamelContext(applicationContext);
return camelContext;
}
spring 拾取组件并创建,该部件很好 . 我可以通过 camelContext.addRoutes(new MyRouteBuilder());
注册路线 . 唯一缺少的是如果将它作为一个 spring bean进行管理,如何告诉驼峰上下文获取路由 .
2 回答
您的方法不起作用,因为您没有使用CamelContextFactoryBean创建驼峰上下文 . 这是隐藏逻辑的地方,它在类路径中查找Spring Bean Camel Routes .
解决这个问题最简单的方法是添加一个引用这个工厂bean的基于xml的Spring上下文配置!
或者,您可以尝试从Application类中调用工厂bean(请参阅此链接:FactoryBeans and the annotation-based configuration in Spring 3.0),但是从
@Configuration
类调用工厂bean很棘手,因为它们都是不构建兼容性的机制的一部分 . 特别是,因为CamelContextFactoryBean
也在实施InitialisingBean
.事实证明我非常接近解决方案 . 我所要做的就是在我已经拥有的CamelConfiguration类中添加一个ComponentScan注释 .
然后从我的Application类中删除
public SpringCamelContext camelContext(ApplicationContext applicationContext)
.就是这样 - RouteBuilder会自动被选中 .