3.2. Spring Boot


Spring Boot automatically configures Camel for you. The opinionated autoconfiguration of the Camel context auto-detects Camel routes available in the Spring context and registers the key Camel utilities (like producer template, consumer template and the type converter) as beans.

Maven users will need to add the following dependency to their pom.xml in order to use this component:

<dependency>
    <groupId>org.apache.camel.springboot</groupId>
    <artifactId>camel-spring-boot</artifactId>
</dependency>

camel-spring-boot jar comes with the spring.factories file, so as soon as you add that dependency into your classpath, Spring Boot will automatically auto-configure Camel for you.

3.2.1. Camel Spring Boot Starter

Apache Camel ships a Spring Boot Starter module that allows you to develop Spring Boot applications using starters.

There is also a sample application available in the examples repository.

To use the starter, add the following to your spring boot pom.xml file:

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

Then you can just add classes with your Camel routes such as:

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");
    }
}

Then these routes will be started automatically.

You can customize the Camel application in the application.properties or application.yml file.

3.2.2. Spring Boot Auto-configuration

When using spring-boot with Spring Boot make sure to use the following Maven dependency to have support for auto configuration:

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

3.2.3. Auto-configured Camel context

The most important piece of functionality provided by the Camel auto-configuration is the CamelContext instance. Camel auto-configuration creates a SpringCamelContext for you and takes care of the proper initialization and shutdown of that context. The created Camel context is also registered in the Spring application context (under the camelContext bean name), so you can access it like any other Spring bean.

@Configuration
public class MyAppConfig {

  @Autowired
  CamelContext camelContext;

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

}

3.2.4. Auto-detecting Camel routes

Camel auto-configuration collects all the RouteBuilder instances from the Spring context and automatically injects them into the provided CamelContext. This means that creating new Camel routes with the Spring Boot starter is as simple as adding 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 creating 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");
      }

    };
  }

}

3.2.5. Camel properties

Spring Boot auto-configuration automatically connects to Spring Boot external configuration (which may contain properties placeholders, OS environment variables or system properties) with the Camel properties support. It basically means that any property defined in application.properties file:

route.from = jms:invoices

Or set via system property:

java -Droute.to=jms:processed.invoices -jar mySpringApp.jar

can be used as placeholders in Camel route:

@Component
public class MyRouter extends RouteBuilder {

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

}

3.2.6. Custom Camel context configuration

If you want to perform some operations on CamelContext bean created by Camel auto-configuration, register CamelContextConfiguration instance in your Spring context:

@Configuration
public class MyAppConfig {

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

}

The method beforeApplicationStart will be called just before the Spring context is started, so the CamelContext instance passed to this callback is fully auto-configured. If you add multiple instances of CamelContextConfiguration into your Spring context, each instance is executed.

작은 정보

For a sample application, see the Metrics example in the camel-spring-boot-examples repository.

3.2.7. Auto-configured consumer and producer templates

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

@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 modifying the following Spring properties:

camel.springboot.consumer-template-cache-size = 100
camel.springboot.producer-template-cache-size = 200

3.2.8. Auto-configured TypeConverter

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

@Component
public class InvoiceProcessor {

  @Autowired
  private TypeConverter typeConverter;

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

}

3.2.8.1. Spring type conversion API bridge

Spring comes with the powerful type conversion API. The Spring API is similar to the Camel type converter API. As both APIs are so similar, 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 like Camel ones. With this approach you can use both Camel and Spring converters accessed via Camel TypeConverter API:

@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());
  }

}

Under the hood Camel 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 will create one for you.

작은 정보

For a sample application, see the Type converter example in the camel-spring-boot-examples repository.

3.2.9. Keeping the application alive

Camel applications which have this feature enabled launch a new thread on startup for the sole purpose of keeping the application alive by preventing JVM termination. This means that after you start a Camel application with Spring Boot, your application waits for a Ctrl+C signal and does not exit immediately.

The controller thread can be activated using the camel.springboot.main-run-controller to true.

camel.springboot.main-run-controller = true

Applications using web modules (for example, applications that import the org.springframework.boot:spring-boot-web-starter module), usually don’t need to use this feature because the application is kept alive by the presence of other non-daemon threads.

작은 정보

For a sample application, see the POJO example in the camel-spring-boot-examples repository.

3.2.10. Adding XML routes

By default, you can put Camel XML routes in the classpath under the directory camel, which camel-spring-boot will auto-detect and include. You can configure the directory name or turn this off using the configuration option:

# turn off
camel.springboot.routes-include-pattern = false
# scan only in the com/foo/routes classpath
camel.springboot.routes-include-pattern = classpath:com/foo/routes/*.xml

The XML files should be Camel XML routes (not <CamelContext>) such as:

<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>
작은 정보

For a sample application, see the XML example in the camel-spring-boot-examples repository.

3.2.11. Testing the JUnit 5 way

For testing, Maven users will need to add the following dependencies to their pom.xml:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-test-spring-junit5</artifactId>
    <scope>test</scope>
</dependency>

To test a Camel Spring Boot application, annotate your test class(es) with @CamelSpringBootTest. This brings Camel’s Spring Test support to your application, so that you can write tests using Spring Boot test conventions.

To get the CamelContext or ProducerTemplate, you can inject them into the class in the normal Spring manner, using @Autowired.

You can also use camel-test-spring-junit5 to configure tests declaratively. This example uses the @MockEndpoints annotation to auto-mock an endpoint:

@CamelSpringBootTest
@SpringBootApplication
@MockEndpoints("direct:end")
public class MyApplicationTest {

    @Autowired
    private ProducerTemplate template;

    @EndpointInject("mock:direct:end")
    private MockEndpoint mock;

    @Test
    public void testReceive() throws Exception {
        mock.expectedBodiesReceived("Hello");
        template.sendBody("direct:start", "Hello");
        mock.assertIsSatisfied();
    }

}
작은 정보

For a sample application, see the Infinispan example in the camel-spring-boot-examples repository.

The @CamelSpringBootTest extends @SpringBootTest functionality, including features, plus: - Provides route testing utilities - Includes CamelContext, route advisors, and mock endpoints - Enables Camel test annotations - Works with @MockEndpoints, @UseAdviceWith, etc.

An example of @UseAdviceWith is when a route modification is applied at runtime:

package com.redhat;
 ....
import org.apache.camel.test.spring.junit5.CamelSpringBootTest;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 ....
@CamelSpringBootTest
@SpringBootApplication
public class MySpringBootApplicationTest {

	@Autowired
	private CamelContext camelContext;

	@Autowired
	private ProducerTemplate producerTemplate;

	public static void main(String[] args) {
		SpringApplication.run(MySpringBootApplicationTest.class, args);
	}

	// Spring context fixtures
	@Configuration
	static class TestConfig {

		@Bean
		RoutesBuilder route() {
			return new RouteBuilder() {
				@Override
				public void configure() throws Exception {
					from("timer:hello1?period={{timer.period}}").routeId("hello1")
							.transform().method("myBean", "saySomething")
							.filter(simple("${body} contains 'foo'"))
							.to("log:foo")
							.end()
							.to("stream:out");
				}
			};
		}
	}

	@Test
	public void test() throws Exception {
		// Apply advice before getting the mock endpoint
		AdviceWith.adviceWith(camelContext, "hello1",
				// intercepting an exchange on route
				r -> {
					// replacing consumer with direct component
					r.replaceFromWith("direct:start");
					// mocking producer
					r.mockEndpoints("stream*");
				}
		);

		// Start the context after applying advice
		camelContext.start();

		// Get mock endpoint after advice is applied
		MockEndpoint mock = camelContext.getEndpoint("mock:stream:out", MockEndpoint.class);

		// setting expectations
		mock.expectedMessageCount(1);
		mock.expectedBodiesReceived("Hello World");

		// invoking consumer
		producerTemplate.sendBody("direct:start", null);

		// asserting mock is satisfied
		mock.assertIsSatisfied();
	}
}

In some case we need to declare both, a combination of @CamelSpringBootTest and @SpringBootTest, when an applicationContext is strictly required, just adding @SpringBootTest(classes = DocTest.TestApplication.class) to specify which configuration class to use:

package com.redhat;
 ....
import org.apache.camel.EndpointInject;
import org.apache.camel.test.spring.junit5.CamelSpringBootTest;
import org.apache.camel.test.spring.junit5.MockEndpoints;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
 ....
@CamelSpringBootTest
@SpringBootTest(classes = MySpringBootApplicationTest.TestConfig.class)
@SpringBootApplication
@MockEndpoints("direct:end")
public class MySpringBootApplicationTest {

	@Autowired
	private ProducerTemplate template;

	@EndpointInject("mock:direct:end")
	private MockEndpoint mock;

	@Configuration
	static class TestConfig {

		@Bean
		RoutesBuilder route() {
			return new RouteBuilder() {
				@Override
				public void configure() throws Exception {
					from("direct:start").routeId("hello2")
							.setBody(simple("Hello World"))
							.log("Received: ${body}")
							.to("direct:end");

					from("direct:end")
							.log("${body}");
				}
			};
		}
	}

	@Test
	public void testReceive() throws Exception {
		mock.expectedMessageCount(1);
		mock.expectedBodiesReceived("Hello World");
		template.sendBody("direct:start", null);
		mock.assertIsSatisfied();
	}

}

Another approach is to test classic Spring XML context setup. In this case, we need to use @ContextConfiguration to specify the XML file, retrieving the Main Camel runtime context through dependency injection:

@Autowired
protected CamelContext camelContext;

Then, to reloads the Spring ApplicationContext after each test method we can use:

 @DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)

Alternative modes: BEFORE_CLASS, AFTER_CLASS, BEFORE_EACH_TEST_METHOD

A full example is described here:

package com.redhat.plain;
 ....
import org.apache.camel.EndpointInject;
import org.apache.camel.Produce;
import org.apache.camel.test.spring.junit5.CamelSpringBootTest;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ContextConfiguration;
 ....
@CamelSpringBootTest
@ContextConfiguration
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
public class MySpringBootApplicationPlainTest {

	@Autowired
	protected CamelContext camelContext;

	@EndpointInject("mock:a")
	protected MockEndpoint mockA;

	@Produce("direct:start")
	protected ProducerTemplate start;

	@Test
	public void testPositive() throws Exception {
		assertEquals(ServiceStatus.Started, camelContext.getStatus());
		start.sendBody("Hello");
		MockEndpoint.assertIsSatisfied(camelContext);
		mockA.expectedBodiesReceived("Hello");
	}
}

Where Spring XML context requires to be placed under resources at declared class package com.redhat.plain using the naming pattern className-context.xml

Project Structure

src/
├── main/ [yaml context structure]
│   ├── java/
│   │   └─── com/redhat/
│   │        ├── Application.java
│   │        └── route/
│   │            └── MyRoute.java
│   │
│   └── resources/
│       └── application.yml
└── test/ [xml context structure]
    ├── java/
    │   └─ com/redhat/plain
    │      ├── MySpringBootApplicationPlainTest.java
    │      └── route/
    │           └── MyRoute.java
    └── resources/
        └── com/redhat/plain
            └── MySpringBootApplicationPlainTest-context.xml

XML declaration for the example above:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
		xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://camel.apache.org/schema/spring http://camel.apache.org/schema/spring/camel-spring.xsd
    ">

	<!-- Camel Context configuration -->
	<camelContext id="camelContext" xmlns="http://camel.apache.org/schema/spring">

		<route xmlns="http://camel.apache.org/schema/spring" id="helloX">
			<from id="from1" uri="direct:start"/>
			<filter id="filter1">
				<simple>${body} contains 'foo'</simple>
				<to id="to1" uri="log:foo"/>
			</filter>
			<to id="to2" uri="stream:out"/>
		</route>

	</camelContext>

</beans>
Red Hat logoGithubredditYoutubeTwitter

자세한 정보

평가판, 구매 및 판매

커뮤니티

Red Hat 소개

Red Hat은 기업이 핵심 데이터 센터에서 네트워크 에지에 이르기까지 플랫폼과 환경 전반에서 더 쉽게 작업할 수 있도록 강화된 솔루션을 제공합니다.

보다 포괄적 수용을 위한 오픈 소스 용어 교체

Red Hat은 코드, 문서, 웹 속성에서 문제가 있는 언어를 교체하기 위해 최선을 다하고 있습니다. 자세한 내용은 다음을 참조하세요.Red Hat 블로그.

Red Hat 문서 정보

Legal Notice

Theme

© 2026 Red Hat
맨 위로 이동