Using CDI Beans in Camel Routes

The Camel component provides a convenient and powerful mechanism for routing between SwitchYard services using Java DSL or XML routing definitions.  When creating these routes, it's often necessary to add logic to the service pipeline that is specific to the Camel route.  For example, you may want to set or get a header value on the underlying message which is used to instruct routing behavior.   Representing this functionality as a service is a bit of overkill and also loses some of the nice bean integration features of Camel.  To address this need, we have added support for wiring the CDI Bean Manager into Camel as a registry provider.  This means you can add a CDI bean to your application and call that as a bean from within your Camel route to do whatever you want.


Take the following Camel route:

 

public void configure() {
        from("switchyard://SomeService")
            .split(body(String.class).tokenize("\n"))
            .to("bean:special")
            .to("switchyard://AnotherService?operationName=process");
}

 

The bean named "MyBean" is resolved using the CDI BeanManager, so all you have to do is add a CDI bean to your application with this name.

 

@Named("special")
public class MyBean {
    public void foo(Message message) {
        message.setHeader("special", "sauce");
    }
}

 

Check out the Apache Camel pages on bean binding and bean component for more information on how this powerful feature can be used.