Friday, August 23, 2013

Taste of Apache Camel: Part II - Using Beans

In my previous post I showed how to use Property Placeholder. Next we'll look into using Beans. They can be used in few ways mentioned on Apache Camel page.
Lets make a new Maven project and pom.xml should look something like this:
This time blueprint.xml will not be necessary, unless you want to run it in container like Karaf or Fuse.
To demonstare how beans work, lets create one.
The bean is very simple. It has only one method that prints out content of route body. This method also has annotation @Handler to indicate that this method should be used for Bean Binding. This has an advantage as you need not specify a method name in the Camel route, and therefore do not run into problems after renaming the method in an IDE that can't find all its references.

Example 1:


The route is simple, too.
The component timer fires and generate message exchanges. Here route is fired every 10 seconds with initial delay of 10 seconds. Parameter repeatCount specifies a maximum limit of number of fires, where zero or negative means fire forever. Timer component is part of camel-core, but for more advanced features camel-quartz could be used.
Body for the route is here set to some hardcoded string, and our bean will get it as parameter to the method. Bean is invoked as endpoint with .bean(). This is enough. Camel knows which method to use, because it is annotated with @Handler annotation.

Example 2:


Lets make another method in out ExampleBean bean. This time method is not annotated, because only one per bean is allowed. This method has two parameters and returns another string.
Now let make another route in configure() method in our route builder class. Here we specified which method from our bean route must use. In double quotes method name must be specified and what the values of parameters will be. If you would like to know how Bean Binding works in more details, go here. When route is started, it should be accessible on url http://localhost:2208/beanexample2/{name}/{surname} and it should return an answer that answerMe method in ExampleBean put together.
Here we see that bean changed body value of out route just by returning some value. The same way the body can be converted to some other type as I will demonstrate in one of my future posts.

My posts on APache Camel:
 - Part I - Property Placeholder
 - Part II - Using Beans
 - Part III - More on using Beans
 - Part IV - Solr
 - Part V - Marshalling and Unmarshalling

No comments:

Post a Comment