Search

Chapter 6. Running Apache Camel application in Spring Boot

download PDF

The Apache Camel Spring Boot component automatically configures Camel context for Spring Boot. Auto-configuration of the Camel context automatically detects the Camel routes available in the Spring context and registers the key Camel utilities such as producer template, consumer template, and the type converter as beans. The Apache Camel component includes a Spring Boot starter module that allows you to develop Spring Boot applications by using starters.

6.1. Introduction to the Camel Spring Boot component

Every Camel Spring Boot application must use the dependencyManagement element in the project’s pom.xml to specify the productized versions of the dependencies. These dependencies are defined in the Red Hat Fuse BOM and are supported for the specific version of Red Hat Fuse. You can omit the version number attribute for the additional starters so as not to override the versions from BOM. See quickstart pom for more information.

Example

<dependencyManagement>
	<dependencies>
		<dependency>
			<groupId>org.jboss.redhat-fuse</groupId>
			<artifactId>fuse-springboot-bom</artifactId>
			<version>${fuse.version}</version>
			<type>pom</type>
			<scope>import</scope>
		</dependency>
	</dependencies>
</dependencyManagement>

Note

The camel-spring-boot jar contains with the spring.factories file which allows you to add that dependency to your classpath so Spring Boot will automatically configure Camel context.

6.2. Introduction to the Camel Spring Boot starter module

Starters are the Apache Camel modules that are intended to be used in Spring Boot applications. There is a camel-xxx-starter module for each Camel component (with a few exceptions listed in the Section 6.3, “List of the Camel components that do not have starter modules” section).

Starters meet the following requirements:

  • Allow auto-configuration of the component by using the native Spring Boot configuration system which is compatible with IDE tooling.
  • Allow auto-configuration of data formats and languages.
  • Manage transitive logging dependencies to integrate with the Spring Boot logging system.
  • Include additional dependencies and align transitive dependencies to minimize the effort of creating a working Spring Boot application.

Each starter has its own integration test in tests/camel-itest-spring-boot, that verifies the compatibility with the current release of Spring Boot.

Note

For more details, see link: Apache Camel Spring-Boot examples.

6.3. List of the Camel components that do not have starter modules

The following components do not have starter modules because of compatibility issues:

  • camel-blueprint (intended for OSGi only)
  • camel-cdi (intended for CDI only)
  • camel-core-osgi (intended for OSGi only)
  • camel-ejb (intended for JEE only)
  • camel-eventadmin (intended for OSGi only)
  • camel-ibatis (camel-mybatis-starter is included)
  • camel-jclouds
  • camel-mina (camel-mina2-starter is included)
  • camel-paxlogging (intended for OSGi only)
  • camel-quartz (camel-quartz2-starter is included)
  • camel-spark-rest
  • camel-openapi-java (camel-openapi-java-starter is included)

6.4. Using Camel Spring Boot starter

Apache Camel provides a starter module that allows you to quickly get started developing Spring Boot applications.

Procedure

  1. Add the following dependency to your Spring Boot pom.xml file:

    <dependency>
        <groupId>org.apache.camel</groupId>
        <artifactId>camel-spring-boot-starter</artifactId>
    </dependency>
  2. Add the classes with your Camel routes as shown in the snippet below. Once these routes are added to the class path the routes are started automatically.

    package com.example;
    
    import org.apache.camel.builder.RouteBuilder;
    import org.springframework.stereotype.Component;
    
    @Component
    public class MyRoute extends RouteBuilder {
    
        @Override
        public void configure() throws Exception {
            from("timer:foo")
              .to("log:bar");
        }
    }
  3. Optional. To keep the main thread blocked so that Camel stays up, do one of the following.

    1. Include the spring-boot-starter-web dependency,
    2. Or add camel.springboot.main-run-controller=true to your application.properties or application.yml file.

      You can customize the Camel application in the application.properties or application.yml file with camel.springboot.* properties.

  4. Optional. To refer to a custom bean by using the bean’s ID name, configure the options in the src/main/resources/application.properties (or the application.yml) file. The following example shows how the xslt component refers to a custom bean by using the bean ID.

    1. Refer to a custom bean by the id myExtensionFactory.

      camel.component.xslt.saxon-extension-functions=myExtensionFactory
    2. Then create the custom bean using Spring Boot @Bean annotation.

      @Bean(name = "myExtensionFactory")
      public ExtensionFunctionDefinition myExtensionFactory() {
          }

      Or, for a Jackson ObjectMapper, in the camel-jackson data-format:

      camel.dataformat.json-jackson.object-mapper=myJacksonMapper

6.5. About Camel context auto-configuration for Spring Boot

Camel Spring Boot auto-configuration provides a CamelContext instance and creates a SpringCamelContext. It also initializes and performs shutdown of that context. This Camel context is registered in the Spring application context under camelContext bean name and you can access it like other Spring bean. You can access the camelContext as shown below.

Example

@Configuration
public class MyAppConfig {

  @Autowired
  CamelContext camelContext;

  @Bean
  MyService myService() {
    return new DefaultMyService(camelContext);
  }

}

6.6. Auto-detecting Camel routes in Spring Boot Applications

Camel auto-configuration collects all the RouteBuilder instances from the Spring context and automatically injects them into the CamelContext. This simplifies the process of creating a new Camel route with the Spring Boot starter. You can create the routes as follows:

Example

Add the @Component annotated class to your classpath.

@Component
public class MyRouter extends RouteBuilder {

  @Override
  public void configure() throws Exception {
    from("jms:invoices").to("file:/invoices");
  }

}

Or create a new route RouteBuilder bean in your @Configuration class.

@Configuration
public class MyRouterConfiguration {

  @Bean
  RoutesBuilder myRouter() {
    return new RouteBuilder() {

      @Override
      public void configure() throws Exception {
        from("jms:invoices").to("file:/invoices");
      }

    };
  }
 
}

6.7. Configuring Camel properties for Camel Spring Boot auto-configuration

Spring Boot auto-configuration connects to the Spring Boot external configuration such as properties placeholders, OS environment variables, or system properties with Camel properties support.

Procedure

  1. Define the properties either in the application.properties file:  

    route.from = jms:invoices

    Or set the Camel properies as the system properties, for example:

    java -Droute.to=jms:processed.invoices -jar mySpringApp.jar
  2. Use the configured properties as placeholders in Camel route as follows.

    @Component
    public class MyRouter extends RouteBuilder {
    
      @Override
      public void configure() throws Exception {
        from("{{route.from}}").to("{{route.to}}");
      }
    
    }

6.8. Configuring custom Camel context

To perform operations on the CamelContext bean created by Camel Spring Boot auto-configuration, register a CamelContextConfiguration instance in your Spring context.

Procedure

  • Register an instance of CamelContextConfiguration in the Spring context as shown below.

    @Configuration
    public class MyAppConfig {
    
      ...
    
      @Bean
      CamelContextConfiguration contextConfiguration() {
        return new CamelContextConfiguration() {
          @Override
          void beforeApplicationStart(CamelContext context) {
            // your custom configuration goes here
          }
        };
      }
    
    }

The CamelContextConfiguration and beforeApplicationStart(CamelContext) methods are called before the Spring context is started, so the CamelContext instance that is passed to this callback is fully auto-configured. You can add many instances of CamelContextConfiguration into your Spring context and all of them will be executed.

6.9. Disabling JMX in the auto-configured CamelContext

To disable JMX in the auto-configured CamelContext, you can use the camel.springboot.jmxEnabled property as JMX is enabled by default.

Procedure

  • Add the following property to your application.properties file and set it to false:

    camel.springboot.jmxEnabled = false

6.10. Injecting auto-configured consumer and producer templates into Spring-managed beans

Camel auto-configuration provides pre-configured ConsumerTemplate and ProducerTemplate instances. You can inject them into your Spring-managed beans.

Example

@Component
public class InvoiceProcessor {

  @Autowired
  private ProducerTemplate producerTemplate;

  @Autowired
  private ConsumerTemplate consumerTemplate;
  public void processNextInvoice() {
    Invoice invoice = consumerTemplate.receiveBody("jms:invoices", Invoice.class);
    ...
    producerTemplate.sendBody("netty-http:http://invoicing.com/received/" + invoice.id());
  }

}

By default consumer templates and producer templates come with the endpoint cache sizes set to 1000. You can change these values by setting the following Spring properties to the desired cache size, for example:

camel.springboot.consumerTemplateCacheSize = 100
camel.springboot.producerTemplateCacheSize = 200

6.11. About the auto-configured TypeConverter in the Spring context

Camel auto-configuration registers a TypeConverter instance named typeConverter in the Spring context.

Example

@Component
public class InvoiceProcessor {

  @Autowired
  private TypeConverter typeConverter;

  public long parseInvoiceValue(Invoice invoice) {
    String invoiceValue = invoice.grossValue();
    return typeConverter.convertTo(Long.class, invoiceValue);
  }

}

6.12. Spring type conversion API bridge

Spring consist of a powerful type conversion API. Spring API is similar to the Camel type converter API. Due to the similarities between the two APIs Camel Spring Boot automatically registers a bridge converter (SpringTypeConverter) that delegates to the Spring conversion API. This means that out-of-the-box Camel will treat Spring Converters similar to Camel.

This allows you to access both Camel and Spring converters using the Camel TypeConverter API, as shown below:

Example

@Component
public class InvoiceProcessor {

  @Autowired
  private TypeConverter typeConverter;

  public UUID parseInvoiceId(Invoice invoice) {
    // Using Spring's StringToUUIDConverter
    UUID id = invoice.typeConverter.convertTo(UUID.class, invoice.getId());
  }

}

Here, Spring Boot delegates conversion to the Spring’s ConversionService instances available in the application context. If no ConversionService instance is available, Camel Spring Boot auto-configuration creates an instance of ConversionService.

6.13. Disabling type conversions features

To disable the Camel Spring Boot type conversion features, set the camel.springboot.typeConversion property to false. When this property is set to false, the auto-configuration does not register a type converter instance and does not enable the delegation of type conversion to the Spring Boot type conversion API.

Procedure

  • To disable the type conversion features of Camel Spring Boot component, set the camel.springboot.typeConversion property to false as shown below:

    camel.springboot.typeConversion = false

6.14. Adding XML routes to the classpath for auto-configuration

By default, the Camel Spring Boot component auto-detects and includes the Camel XML routes that are in the classpath in the camel directory. You can configure the directory name or disable this feature using the configuration option.

Procedure

  • Configure the Camel Spring Boot XML routes in the classpath as follows.

    // turn off
    camel.springboot.xmlRoutes = false
    // scan in the com/foo/routes classpath
    camel.springboot.xmlRoutes = classpath:com/foo/routes/*.xml
    Note

    The XML files should define the Camel XML route elements and not CamelContext elements, for example:

       <routes xmlns="http://camel.apache.org/schema/spring">
            <route id="test">
                <from uri="timer://trigger"/>
                <transform>
                    <simple>ref:myBean</simple>
                </transform>
                <to uri="log:out"/>
            </route>
        </routes>

Using Spring XML files

To use Spring XML files with the <camelContext>, you can configure a Camel context in the Spring XML file or in the application.properties file. To set the name of the Camel context and turn on the stream caching, add the following in the application.properties file:

camel.springboot.name = MyCamel
camel.springboot.stream-caching-enabled=true

6.15. Adding XML Rest-DSL Routes for auto-configuration

The Camel Spring Boot component auto-detects and embeds the Camel Rest-DSL XML routes that are added in the classpath under the camel-rest directory. You can configure the directory name or disable this feature using the configuration option.

Procedure

  • Configure the Camel Spring Boot Rest-DSL XML routes in the classpath as follows.

    // turn off
    camel.springboot.xmlRests = false
    // scan in the com/foo/routes classpath
    camel.springboot.xmlRests = classpath:com/foo/rests/*.xml
    Note

    The Rest-DSL XML files should define the Camel XML REST elements and not CamelContext elements, for example:

       <rests xmlns="http://camel.apache.org/schema/spring">
          <rest>
             <post uri="/persons">
                <to uri="direct:postPersons"/>
             </post>
             <get uri="/persons">
                <to uri="direct:getPersons"/>
             </get>
             <get uri="/persons/{personId}">
                 <to uri="direct:getPersionId"/>
             </get>
             <put uri="/persons/{personId}">
                 <to uri="direct:putPersionId"/>
             </put>
             <delete uri="/persons/{personId}">
                 <to uri="direct:deletePersionId"/>
             </delete>
          </rest>
        </rests>

6.16. Testing with Camel Spring Boot

When Camel runs on the Spring Boot, Spring Boot automatically embeds Camel and all its routes, which are annotated with @Component. When testing with Spring Boot use @SpringBootTest instead of @ContextConfiguration to specify which configuration class to use.

When you have multiple Camel routes in different RouteBuilder classes, the Camel Spring Boot component automatically embeds all these routes when running the application. Hence, when you wish to test routes from only one RouteBuilder class you can use the following patterns to include or exclude which RouteBuilders to enable:

  • java-routes-include-pattern: Used for including RouteBuilder classes that match the pattern.
  • java-routes-exclude-pattern: Used for excluding RouteBuilder classes that match the pattern. Exclude takes precedence over include.

Procedure

  1. Specify the include or exclude patterns in your unit test classes as properties to @SpringBootTest annotation, as shown below:

    @RunWith(CamelSpringBootRunner.class)
    @SpringBootTest(classes = {MyApplication.class);
       properties = {"camel.springboot.java-routes-include-pattern=**/Foo*"})
    public class FooTest {

    In the FooTest class, the include pattern is **/Foo*, which represents an Ant style pattern. Here, the pattern starts with a double asterisk, which matches with any leading package name. /Foo* means the class name must start with Foo, for example, FooRoute.

  2. Run the test using the following maven command:

    mvn test -Dtest=FooTest

6.17. Using Spring Boot, Apache Camel and external messaging brokers

Fuse uses external messaging brokers. See Supported Configurations for more information about the supported broker, client and Camel component combinations.

The Camel component must be connected to the JMS connection-factory. The example below shows how to connect the camel-amqp component to a JMS connection-factory.

import org.apache.activemq.jms.pool.PooledConnectionFactory;
import org.apache.camel.component.amqp.AMQPComponent;
import org.apache.qpid.jms.JmsConnectionFactory;
...

AMQPComponent amqpComponent(AMQPConfiguration config) {
       JmsConnectionFactory qpid = new JmsConnectionFactory(config.getUsername(), config.getPassword(), "amqp://"+ config.getHost() + ":" + config.getPort());
       qpid.setTopicPrefix("topic://");

       PooledConnectionFactory factory = new PooledConnectionFactory();
       factory.setConnectionFactory(qpid);

AMQPComponent amqpcomp = new AMQPComponent(factory);
Red Hat logoGithubRedditYoutubeTwitter

Learn

Try, buy, & sell

Communities

About Red Hat Documentation

We help Red Hat users innovate and achieve their goals with our products and services with content they can trust.

Making open source more inclusive

Red Hat is committed to replacing problematic language in our code, documentation, and web properties. For more details, see the Red Hat Blog.

About Red Hat

We deliver hardened solutions that make it easier for enterprises to work across platforms and environments, from the core datacenter to the network edge.

© 2024 Red Hat, Inc.