Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

As of 2.10 we now have support for Contexts and Dependency Injection - JSR299 and Dependency Injection for Java - JSR330 as a dependency injection framework. This offers new opportunities to develop and deploy Apache Camel projects in Java EE 6 containers but also in standalone Java SE or CDI container

The current project is under active development and does not provide all the features that we have with injection frameworks like Spring or Blueprint

Dependency Injecting Camel with CDI

The GuiceCamelContext is designed to work nicely inside Guice. You then need to bind it using some Guice Module.

The camel-guice library comes with a number of reusable Guice Modules you can use if you wish - or you can bind the GuiceCamelContext yourself in your own module.

  • CamelModule is the base module which binds the GuiceCamelContext but leaves it up you to bind the RouteBuilder instances
  • CamelModuleWithRouteTypes extends CamelModule so that in the constructor of the module you specify the RouteBuilder classes or instances to use
  • CamelModuleWithMatchingRoutes extends CamelModule so that all bound RouteBuilder instances will be injected into the CamelContext or you can supply an optional Matcher to find RouteBuilder instances matching some kind of predicate.

So you can specify the exact RouteBuilder instances you want

Code Block

Injector injector = Guice.createInjector(new CamelModuleWithRouteTypes(MyRouteBuilder.class, AnotherRouteBuilder.class));
// if required you can lookup the CamelContext
CamelContext camelContext = injector.getInstance(CamelContext.class);

Or inject them all

Code Block

Injector injector = Guice.createInjector(new CamelModuleWithRouteTypes());
// if required you can lookup the CamelContext
CamelContext camelContext = injector.getInstance(CamelContext.class);

You can then use Guice in the usual way to inject the route instances or any other dependent objects.

Bootstrapping with JNDI

A common pattern used in J2EE is to bootstrap your application or root objects by looking them up in JNDI. This has long been the approach when working with JMS for example - looking up the JMS ConnectionFactory in JNDI for example.

You can follow a similar pattern with Guice using the GuiceyFruit JNDI Provider which lets you bootstrap Guice from a jndi.properties file which can include the Guice Modules to create along with environment specific properties you can inject into your modules and objects.

If the jndi.properties is conflict with other component, you can specify the jndi properties file name in the Guice Main with option -j or -jndiProperties with the properties file location to let Guice Main to load right jndi properties file.

Configuring Component, Endpoint or RouteBuilder instances

You can use Guice to dependency inject whatever objects you need to create, be it an Endpoint, Component, RouteBuilder or arbitrary bean used within a route.

The easiest way to do this is to create your own Guice Module class which extends one of the above module classes and add a provider method for each object you wish to create. A provider method is annotated with @Provides as follows

Basically, two things should be done to use Apache Camel in a CDI environment. First, we just need to create a BootStrap class which will be use by the Java EE 6 container or Java SE to start the Camel Context. The CdiCamelContext when instantiated will add a CDI Bean Registry. That will allow Camel to perform lookup of beans injected and registered in CDI container. Next, we must add CDI annotated beans (@inject, @named, ...) to use them from the Apache Camel routes.

Bootstrapping Camel with CDI container

The following example shows how we can bootstrap an Apache Camel Context in a Boot Strap class. This class contains important annotations like the javax.ejb.Singleton. This annotation will tell the container to create a Singleton instance of the BootStrapClass class. This mechanism is similar to Bean instance creation that we have with Spring framework. By combining this annotation with javax.ejb.Startup, the container will start the camel context at the startup of the CDI container.

Code Block

    @Singleton
    @Startup
    public class BootStrap {
    ...

When the @PreConstruct annotation is called, then we inject a CdiCamelContext objet, register a SimpleCamelRoute using @Inject annotation and starts the Camel Route.

Code Block

    @PostConstruct
    public void init() throws Exception {
            logger.info(">> Create CamelContext and register Camel Route.");

            // Define Timer URI
            simpleRoute.setTimerUri("timer://simple?fixedRate=true&period=10s");

            // Add Camel Route
            camelCtx.addRoutes(simpleRoute);

            // Start Camel Context
            camelCtx.start();

When you look to the following Camel Route code, you can see that we do a lookup to find a bean "helloWorld" which has been injected. This is possible because the CdiCamelContext registers a Camel Registry containing a reference to a CDI BeanManager.

Code Block

    @Override
    public void configure() throws Exception {

        from(timerUri)
            .setBody()
                .simple("Bean Injected")

            // Lookup for bean injected by CDI container
            // The HellowWorld class is annotated using @Named
            .beanRef("helloWorld", "sayHello")

   
Code Block

public class MyModule extends CamelModuleWithMatchingRoutes {

    @Provides
    @JndiBind("jms")
    JmsComponent jms(@Named("activemq.brokerURL") String brokerUrl) {
        return JmsComponent.jmsComponent(new ActiveMQConnectionFactory(brokerUrl));log(">> Response : ${body}");

    }
}

You can optionally annotate the method with @JndiBind to bind the object to JNDI at some name if the object is a component, endpoint or bean you wish to refer to by name in your routes.

You can inject any environment specific properties (such as URLs, machine names, usernames/passwords and so forth) from the jndi.properties file easily using the @Named annotation as shown above. This allows most of your configuration to be in Java code which is typesafe and easily refactorable - then leaving some properties to be environment specific (the jndi.properties file) which you can then change based on development, testing, production etc.

Creating multiple RouteBuilder instances per type

It is sometimes useful to create multiple instances of a particular RouteBuilder with different configurations.

To do this just create multiple provider methods for each configuration; or create a single provider method that returns a collection of RouteBuilder instances.

For example

Here is the code of the HelloWorld Bean

Code Block

@Named
public class HelloWorld
Code Block

import org.apache.camel.guice.CamelModuleWithMatchingRoutes;
import com.google.common.collect.Lists;

public class MyModule extends CamelModuleWithMatchingRoutes {

    @Provides
public String   @JndiBind("foo")
    Collection<RouteBuilder> foo(@Named("fooUrl") String fooUrlsayHello(@Body String message) {
        return Lists.newArrayList(new MyRouteBuilder(fooUrl), new MyRouteBuilder("activemq:CheeseQueue"))">> Hello " + message + " user.";
    }
}

See Also

This project is started using the GlassFish maven plugin but alternatively, you can deploy the war file produced in any Java EE 6 servers : Glassfish, JBoss AS 7, OpenEJB, Apache TomEE or Apache KarafEE or using a Java SE.

See Also