Elegant Camel route configuration

July 3, 2018

I’m a big fan of the Camel Java DSL for defining Camel routes with a RouteBuilder. This is super easy and slim. However, in this blog post I show you a nerdy trick how this can be done even more elegant.

If you are a Camel user, you know, that defining a route for a given Camel context ctx ist just a matter to implement the configure() method of the abstract RouteBuilder class:

ctx.add(new RouteBuilder {

   @Override
   public void configure() throws Exception {
      from("file:data/inbox?noop=true")
        .to("file:data/outbox");
   }

});

Its really simple and you can use the whole Camel machinery from within your configure() method.

However, this kind of configuration can be performed even simpler. Let’s assume that you have a no-op default implementation of RouteBuilder called Routes:

public class Routes extends RouteBuilder {
    @Override
    public void configure() throws Exception { }
}

Then, the configuration can be rewritten simply as

ctx.add(new Routes {{
      from("file:data/inbox?noop=true")
        .to("file:data/outbox");
}});

This trick just uses Java’s object initializers, a not so well known language feature. The inspiration for providing the DSL context like this comes from JMockit which defines its mock expectations the same way. I think object initializers are really an elegant albeit hipster way to implement DSLs.

Although you can easily define the Routes class on your own, you might vote for this Camel issue or pull request if you want to have this in upstream Camel, too.