Processor

The Processor interface is used to implement consumers of message exchanges or to implement a Message Translator, and other use-cases.

Using a processor in a route

Once you have written a class which implements processor like this:

public class MyProcessor implements Processor {

    public void process(Exchange exchange) throws Exception {
        // do something...
    }

}

Then you can easily call this processor from a Java such as:

from("activemq:myQueue").process(new MyProcessor());

Notice that the processor is referred to by the class type MyProcessor.class in the route. Camel will during startup automatic create one new instance of the processor using Injector to be used during routing messages.

In XML DSL however the <process> tag requires, referring to an existing processor instance which can be done:

You can then easily use this inside a route by declaring the bean in Spring, say via the XML:

<bean id="myProcessor" class="com.acme.MyProcessor"/>

And then use the bean id in the Camel route:

<route>
  <from uri="activemq:myQueue"/>
  <process ref="myProcessor"/>
</route>

And in Java DSL:

from("activemq:myQueue").process("myProcessor");

Referring to beans using #class syntax

In XML DSL you can also refer to the processor by its class name using #class: as prefix as shown:

<route>
  <from uri="activemq:myQueue"/>
  <process ref="#class:com.acme.MyProcessor"/>
</route>

This also works in Java DSL:

from("activemq:myQueue").process("#class:com.acme.MyProcessor");
For more details about the #class: prefix (and others) then see Property Binding.

However in Java DSL you would often use the type safe way and instantiate the Processor directly as previously shown:

from("activemq:myQueue").process(new MyProcessor());

Why use process when you can use to instead?

The process can be used in routes as an anonymous inner class such:

    from("activemq:myQueue").process(new Processor() {
        public void process(Exchange exchange) throws Exception {
            String payload = exchange.getIn().getBody(String.class);
            // do something with the payload and/or exchange here
           exchange.getIn().setBody("Changed body");
       }
    }).to("activemq:myOtherQueue");

This is usable for quickly whirling up some code. If the code in the inner class gets a bit more complicated it is of course advised to refactor it into a separate class. This approach is better if you do not want to use this processor again. From reusability perspective, it is not recommended to use this approach with anonymous inner classes.

See Also