This post demonstrates how to use Spring Boot, and Spring DI with Apache Camel and have Spring add routes and start and stop CamelContext automatically.
The Spring way
In the previous post, Spring Boot – Copy File to Another Directory using Apache Camel, I created a Spring Boot application that rely only on the static main method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
@SpringBootApplication public class ComTurretaApacheCamelDemoApplication { public static void main(String[] args) throws Exception { ApplicationContext ctx = SpringApplication.run(ComTurretaApacheCamelDemoApplication.class, args); CamelContext camelContext = (CamelContext)ctx.getBean("camelContext"); camelContext.addRoutes(new MyRouteBuilder()); camelContext.start(); Thread.sleep(60*100); camelContext.stop(); } } |
The only “Spring” codes there is the use of SpringApplication and retrieval of “camelContext” bean from the ApplicationContext
1 |
ApplicationContext ctx = SpringApplication.run(ComTurretaApacheCamelDemoApplication.class, args); |
Let’s rewrite those codes by creating a new Spring Boot application that uses @Configuration, and @Bean (or @Component).
New Spring Boot Application
Our new Spring Boot application has a leaner main class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
package com.turreta.springboot.apache.camel.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import java.util.concurrent.TimeUnit; @SpringBootApplication public class ComTurretaSpringbootApacheCamelDemoApplication { public static void main(String[] args) { SpringApplication.run(ComTurretaSpringbootApacheCamelDemoApplication.class, args); try { // Sleep for 5 minutes TimeUnit.MINUTES.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } } } |
Then, create a @Configuration class and @Bean object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
package com.turreta.springboot.apache.camel.demo; import org.apache.camel.RoutesBuilder; import org.apache.camel.builder.RouteBuilder; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Component; @Component public class MyCamelConfiguration { @Bean RoutesBuilder myRouter() { return new RouteBuilder() { @Override public void configure() throws Exception { from("file:/C:/Users/windowuser/Desktop/ksg/blog/Spring%20Boot%20-%20Using%20annotations%20for%20Apache%20Camel/shared/in?move=./processed") .to("file:/C:/Users/windowuser/Desktop/ksg/blog/Spring%20Boot%20-%20Using%20annotations%20for%20Apache%20Camel/shared/out"); } }; } } |
That’s it!
Just drop files to the in directory and Apache Camel will copy them to the out directory.
Testing the new Spring Boot Application
Download the Codes
https://github.com/Turreta/Spring-Boot-Using-annotations-with-Apache-Camel
Recent Comments