apache-camelcdiapache-camel-cdi

camel-cdi how to not auto start CamelContext and not auto discover RouteBuilder


In previous projects i often used Guice also in conjunction with camel. My approach was to extend Camel's Main class and inject my preconfigured context there. I needed to control start of the context. Before start of context i did some preperation (e.g. start hawtio and other setup stuff).

The same i did with RouteBuilder. One central RouteBuilder set up stuff like onException, added RoutePolicies and configured autostart on other routes and of course added all the other routes.

In meantime i learned to love CDI and camel's CDI support in 2.17 (and fuse 6.3) seems to be complete.


Solution

  • So what would be a good approach with camel-cdi to control the start of camel context (deployed as osgi bundle on fuse)?

    Camel CDI always starts the auto-configured Camel contexts. That being said, it is possible to customise these so that routes are not started, by declaring a PostConstruct lifecycle event for example:

    @ApplicationScoped
    class CustomCamelContext extends DefaultCamelContext {
    
        @PostConstruct
        void customize() {
            setAutoStartup(false);
        }
    }
    

    In that example, the routes added to that Camel context won't be started along with the context.

    This respects the Camel principle to start contexts with all the validation that's done at that stage. Yet with the ability to not start the routing.

    How to disable or control autodiscovery of RouteBuilder (and or other stuff)?

    The RoutesBuilder beans qualified with @ContextName are automatically added to the corresponding CamelContext beans by Camel CDI. If no such CamelContext bean exists, it gets automatically created. On the other hand, RoutesBuilder beans qualified with user-defined qualifiers do not trigger the automatic creation of any CamelContext beans. That can be used for Camel routes that may be required to be added later during the application execution. For example with:

    @DoNotDiscover
    class MyRouteBuilder extends RouteBuilder {
        // ...
    }
    

    If no Camel context bean qualified with @DoNotDiscover is explicitly declared, the MyRouteBuilder bean won't be auto-discovered. Still it can be used later during the application execution, e.g.:

    @Inject
    @DoNotDiscover
    Instance<RouteBuilder> routes;
    
    @Inject
    CamelContext context;
    
    for (RouteBuilder route : routes)
        route.addRoutes(route);