Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Camel - Passing specific parameters from routes to a generic bean method

Let's say I have a Camel route that looks like this :

from("direct:myRoute")
        .setHeader("someHeader", simple("some header value"))
        .beanRef("myBean", "beanMethod");

And I have a bean that I cannot change that looks like this :

public class MyBean {
    public void beanMethod(String headerExpected) {
        // do something with the value here.
    }
}

Basically, I want to pass the value of someHeader from myRoute to beanMethod within MyBean.

Knowing that beanMethod can accept a String, how can I pass the value of the header someHeader from the route so that it is accepted as a String within beanMethod?

like image 578
abbasdgr8 Avatar asked May 28 '14 11:05

abbasdgr8


People also ask

How do you pass a parameter to a Camel route?

As you mentioned, you can use a constructor (or setters or any other Java/Framework instruments) if the parameters are static from a Camel point of view. The parameters are configurable in the application, but after the application is started they do no more change.

What is Camel Bean?

Bean as endpoint The source for the bean is just a plain POJO: Camel will use Bean Binding to invoke the sayHello method, by converting the Exchange's In body to the String type and storing the output of the method on the Exchange Out body.

How do I add a bean in Camel context?

You can create an instance of SimpleRegistry where you can add your custom bean. And then pass in the simple registry instance to where you create CamelContext with the new DefaultCamelContext(myRegistry) constructor.


1 Answers

The answers seem to be a bit outdated. Here is how I do, the modern Camel way. You can retrieve the header value within a bean with the @Headers annotation, and you can call the bean method with passing the class and the method name;

Route Class

public class MyRoute extends RouteBuilder {

    @Override
    public void configure() throws Exception {
        from("direct:myRoute")
            .setHeader("myHeader", simple("my header value"))
            .bean(MyBean.class, "handle");
    }

}

Bean Class

public class MyBean {
    
    public static void handle(@Header("myHeader") String headerVal) {
        // do something with header
        System.out.println("myHeader: " + headerVal);
    }

}
like image 122
Levent Divilioglu Avatar answered Sep 18 '22 12:09

Levent Divilioglu