Add camel route at runtime in Java

Himanshu Yadav picture Himanshu Yadav · May 4, 2012 · Viewed 28.4k times · Source

How can I add a camel route at run-time in Java? I have found a Grails example but I have implement it in Java.

My applicationContext.xml already has some predefined static routes and I want to add some dynamic routes to it at run time. Is it possible? Because the only way to include dynamic route is to write the route.xml and then load the route definition to context. How will it work on existing static routes? Route at runtime

Answer

Ben ODay picture Ben ODay · May 4, 2012

you can simply call a few different APIs on the CamelContext to add routes...something like this

context.addRoutes(new MyDynamcRouteBuilder(context, "direct:foo", "mock:foo"));
....
private static final class MyDynamcRouteBuilder extends RouteBuilder {
    private final String from;
    private final String to;

    private MyDynamcRouteBuilder(CamelContext context, String from, String to) {
        super(context);
        this.from = from;
        this.to = to;
    }

    @Override
    public void configure() throws Exception {
        from(from).to(to);
    }
}

see this unit test for the complete example...

https://svn.apache.org/repos/asf/camel/trunk/camel-core/src/test/java/org/apache/camel/builder/AddRoutesAtRuntimeTest.java