How to use Dependency Injection / CDI with Camel routes
Environment
Red Hat JBoss Fuse 6.2.1
Issue
Camel-on-EAP (wildfly-camel) has offers Camel routes combined with JEE components. There are oddities about how DI can be used, though.
Resolution
Be aware of these:
When working with Servlets
This will not work:
@Inject
@ContextName("my-context")
private CamelContext camelContext;
The context referred to is a Spring Camel context which is not @Injectable. This construct applies only to CDI beans (i.e a CDI Camel context).
If you modified the servlet to @Resource inject the desired camel context, it should work fine:
@Resource(name = "java:jboss/camel/context/my-context")
private CamelContext other;
When working with Servlets and @Resource injection of CDI Camel contexts into the servlet, this seems to work well with 'name', but not with 'mappedName' or 'lookup' attributes.
When working with a web service implementation
Resource injecting using the 'name' attribute does not work in web services. E.g:
@Resource(name = "java:jboss/camel/context/my-context")
However, using the 'lookup' attribute works fine:
@Resource(lookup = "java:jboss/camel/context/my-context")
This solution is part of Red Hat’s fast-track publication program, providing a huge library of solutions that Red Hat engineers have created while supporting our customers. To give you the knowledge you need the instant it becomes available, these articles may be presented in a raw and unedited form.
Welcome! Check out the Getting Started with Red Hat page for quick tours and guides for common tasks.
