apache camel documentation describes how to register a route builder with @Component and SpringRouteBuilder and then jumps to the xml code to do
<camelContext xmlns="http://camel.apache.org/schema/spring">
<!-- and then let Camel use those @Component scanned route builders -->
<contextScan/>
</camelContext>
How can I do the same with java config? I've got
package x.y.camel;
@Component
public class MyRouteBuilder extends SpringRouteBuilder {...}
and
@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;
}
The component is picked up by spring and created, that part is fine. I can register the route by camelContext.addRoutes(new MyRouteBuilder());
. The only bit is missing is how to tell camel context to pick up the route if it's managed as a spring bean.
Your approach does not work, because you don't create your camel context with the CamelContextFactoryBean . This is where the logic is hidden that looks for Spring Bean Camel Routes in your classpath.
The easiest solution to the problem is to add a xml-based Spring context configuration that references this factory bean!
Alternatively, you can try calling the factory bean from your Application class (see this link: FactoryBeans and the annotation-based configuration in Spring 3.0 ), but calling a factory bean from a @Configuration
class is tricky, because they are both part of mechanisms that are not build for compatibility. Especially, since CamelContextFactoryBean
is also implementing InitialisingBean
.
It turns out I was pretty close to the solution. All I had to do is to add a ComponentScan annotation on my CamelConfiguration class that I already had.
@Configuration
@ComponentScan("x.y.camel")
public class CamelConfig extends CamelConfiguration {
}
And then remove public SpringCamelContext camelContext(ApplicationContext applicationContext)
from my Application class.
That's it - the RouteBuilder is picked up automatically.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.