Gert Vanthienen's blog

Monday, October 11, 2010

Traits in the Camel Scala DSL

When using the Java DSL for Camel, you can create a custom RouteBuilder class which defines common elements for all your routes (e.g. standardized error handling). Since you're only able to inherit from a single class, great care must be taken in which common route elements are being added to the parent class.

The Scala DSL allows you to extract those common route elements into traits, which can be mixed into the RouteBuilder in more flexible ways. Consider the scenario where we have two ways we do our error handling: we either want to write a message to the error log or we want to send the message into an error queue.

We can model this by writing two Scala traits, defining the org.apache.camel.scala.dsl.RouteBuilder class as the trait's self type:

trait ErrorQueue { self: RouteBuilder =>
handle[Exception] {
log("Sending ${id} to error queue")


trait ErrorLog { self: RouteBuilder =>

handle[Exception] {
log("Sending ${id} to error log")


Afterwards, we can just add the implementation we want in our own RouteBuilder using a simple with clause.

class MyRouteBuilder extends RouteBuilder
with ErrorLog {

//rest of the route goes here


Just replace the with ErrorLog by with ErrorQueue to pick another error handler implementation. And because you can add multiple traits to the same class, this approach allows you to define lots of common route elements and just mix and match those that you need.

Happy Camel riding with the Scala DSL!!