Camel Guice
As of 1.5 we now have support for Google Guice as a dependency injection framework.
To use it just be dependent on camel-guice.jar which also depends on
- camel-core.jar
- commons-logging.jar
Dependency Injecting Camel with Guice
The GuiceCamelContext is designed to work nicely inside Guice; though there's also the CamelModule which automatically creates a Guice-aware CamelContext, using Guice as the injector to create any of the default strategies, Component or Endpoint instances.
When you create a CamelModule you can specify a list of RouteBuilder classes which will then be dependency injected and installed.
Code Block |
---|
Injector injector = Guice.createInjector(new CamelModule(MyRouteBuilder.class, AnotherRouteBuilder.class));
CamelContext camelContext = injector.getInstance(CamelContext.class);
camelContext.start();
|
You can then use Guice in the usual way to inject the route instances or any other dependent objects.
Custom binding of RouteBuilder
You can create your own derivation of CamelModule which overloads the configureRoutes() method to allow you to use the Multibinder in Guice to bind different route builders.
Code Block |
---|
public static class MyModule extends CamelModule {
/**
* Lets add the routes
*/
@Override
protected void configureRoutes(Multibinder<Routes> binder) {
binder.addBinding().to(MyHardcodeRoute.class);
binder.addBinding().to(MyRouteInstaller.class);
}
}
|
Creating multiple RouteBuilder instances per type
In addition to the above mechanism of binding explicit instances, its sometimes useful to use a single RouteBuilder as a factory of other route builder instances.
This is because the configure() method on a RouteBuilder is called after the CamelContext is created and it is bound to a CamelContext, so you can resolve any components or endpoint dynamically through the CamelContext (using Guice under the covers for any dependency injection).
The following example shows how we can add multiple instances of a RouteBuilder class with different parameters. We can clearly dependency inject the MyRouteInstaller from Guice and use those values to pass into the RouteBuilder instances.
Code Block |
---|
public class MyRouteInstaller extends RouteBuilder {
public void configure() throws Exception {
addRoutes(new MyConfigurableRoute(endpoint("direct:a"), endpoint("direct:b")));
addRoutes(new MyConfigurableRoute(endpoint("direct:c"), endpoint("direct:d")));
}
}
|
...