Spring Boot + Apache Camel = Web Service

Recently I’ve been struggling with a problem how to connect code based on Apache Camel with Spring Boot and expose it as a web service.

Here is my story describing my implementation basing on a simple example. You may find the code in the repository below.

Dependencies

In order to enable Apache Camel in our Spring Boot application we need to add a dependency to camel-spring-boot-starter. Here is a Maven example.

<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-spring-boot-starter</artifactId>
<version>2.17.0</version>
</dependency>

Spring Boot application

Let’s start from the code responsible for running the Spring Boot application. In this case it’s pretty straightforward.

Creating Camel routes

If we annotate our class with the Camel route definition using @Component annotation, Spring Boot will add the route to the Camel context as well.

Web Service

Now comes the best part. We will create a web service which will receive HTTP requests and put the message into the Camel route. After receiving a processed message from the Camel route we need to return HTTP response as well. Let’s see an example on how to achieve it.

The ProducerTemplate object is used for sending messages into the Camel route. We need to build the Camel Exchange object using data from HttpServletRequest.

Unit testing Camel routes

The Apache Camel Spring Testing page describes three approaches for testing Spring with Camel. I used CamelSpringTestSupport class in my unit test. Let’s see an example.

When we are extending CamelSpringTestSupport class, we need to implement createApplicationContxt() method. After doing it, Camel routes will be added to the Camel context automatically.

Conclusion

Using Spring Boot and Apache Camel is pretty simple, however there is lack of good documentation describing the best practice. There is also support for unit testing and again the documentation is not perfect. I’m aware that my solution may not be the best one. Feel free to clone the repo, build the project and comment.