Apache Camel with Spring Boot: how the starter wires everything up

The Camel starter turns a Spring Boot application into a Camel application: it creates the CamelContext, finds your routes and binds camel.* properties. This page explains what it sets up, then runs each part on Spring Boot 4.1: YAML route files, property typos that are silently ignored, applications that exit at once, REST routes under /camel, health checks and route tests.

Contents

What camel-spring-boot-starter sets up

Camel runs on several runtimes: plain Java with Camel Main, Quarkus, and Spring Boot. With Spring Boot, the dependency camel-spring-boot-starter brings Camel's core and a set of auto-configurations. When the application starts, they do four things:

  1. Create one CamelContext as a Spring bean, plus a ProducerTemplate and a ConsumerTemplate that can be injected anywhere.
  2. Find every RouteBuilder bean, such as a @Component class, and add its routes to the context.
  3. Bind camel.* properties from application.properties or YAML: camel.main.* for the context, camel.component.<name>.* for each component, camel.rest.* for the REST DSL.
  4. Make Spring beans visible to Camel: a route can call a bean by name, and {{some.key}} placeholders in routes read Spring's Environment.

Each component has its own starter, such as camel-kafka-starter or camel-servlet-starter, which adds the component and its camel.component.* properties. The core starter already includes the common ones, among them direct, seda, timer, bean, log, file, mock and rest. Camel Spring Boot uses the same version number as Camel itself, and Camel 4.23 runs on Spring Boot 4.1, which means Spring Framework 7 and Jakarta EE 11.

Starters used on this page
StarterAdds
camel-spring-boot-starterCamelContext, core components, camel.main.* properties
camel-yaml-dsl-starterThe YAML DSL, for routes in .yaml files
camel-servlet-starterThe servlet component and CamelServlet, for REST DSL routes on Spring Boot's web server
spring-boot-starter-actuatorHealth endpoints, which Camel's health checks join
camel-test-spring-junit5@CamelSpringBootTest, mock endpoints and AdviceWith support

Every example is a complete Spring Boot 4.1.2 program with Camel 4.23 on Java 21. Each one sets its properties in code with setDefaultProperties, turns off the banner and logging, does its work and closes the context. The programs on this page share one classpath, which includes the web starter, so the ones that need no web server set spring.main.web-application-type=none.

A first application: routes, beans and properties

A price route that calls a Spring service and formats the result with a configured currency shows the three connections between Spring and Camel: route discovery, bean calls and property placeholders:

Java
package demo.camel.first;

import java.util.Map;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.RouteBuilder;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

@SpringBootApplication
public class FirstApp {

    // an ordinary Spring bean, called from a route by its bean name
    @Service("priceService")
    static class PriceService {
        public double priceWithTax(double net) {
            return Math.round(net * 1.2 * 100) / 100.0;
        }
    }

    // every RouteBuilder bean is found and added to the CamelContext
    @Component
    static class PriceRoute extends RouteBuilder {
        @Override
        public void configure() {
            from("direct:price").routeId("price")
                    .bean("priceService", "priceWithTax")
                    .setBody(simple("{{shop.currency}} ${body}"));
        }
    }

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(FirstApp.class);
        app.setDefaultProperties(Map.of(
                // the programs on this page share a classpath that includes Tomcat
                "spring.main.web-application-type", "none",
                "camel.main.name", "shop",
                "shop.currency", "EUR",
                "spring.main.banner-mode", "off",
                "logging.level.root", "OFF"));
        try (var spring = app.run(args)) {
            CamelContext camel = spring.getBean(CamelContext.class);
            System.out.println("CamelContext: name " + camel.getName() + ", Camel "
                    + camel.getVersion() + ", status " + camel.getStatus());
            System.out.println("routes: " + camel.getRoutes().stream()
                    .map(r -> r.getRouteId() + " from " + r.getEndpoint().getEndpointUri())
                    .toList());
            System.out.println("CamelContext is a Spring bean: "
                    + spring.getBeanNamesForType(CamelContext.class).length);

            ProducerTemplate template = spring.getBean(ProducerTemplate.class);
            System.out.println("direct:price with 10.0 -> "
                    + template.requestBody("direct:price", 10.0, String.class));
        }
    }
}
Output
CamelContext: name shop, Camel 4.23.0, status Started
routes: [price from direct://price]
CamelContext is a Spring bean: 1
direct:price with 10.0 -> EUR 12.0
  • The context is called shop, from camel.main.name, and it had started by the time run() returned.
  • The route price was added without any registration code: PriceRoute is a @Component that extends RouteBuilder, and the starter adds every such bean.
  • There is exactly one CamelContext bean, which other beans can inject.
  • .bean("priceService", "priceWithTax") found the @Service("priceService") bean by its Spring bean name and called it with the body, 10.0, giving 12.0.
  • {{shop.currency}} in the Simple expression was resolved from Spring's properties, so the result was EUR 12.0.

Routes can also be written in YAML or XML files instead of Java, as the next section shows.

Routes in YAML files

YAML routes let people change an integration without touching Java code, and are the format Camel's tooling such as Kaoto and Camel JBang writes. The starter loads route files from the locations in camel.main.routes-include-pattern, by default classpath:camel/*, classpath:camel-template/* and classpath:camel-rest/*, when the DSL module for the file type is present. In a project that is camel-yaml-dsl-starter; the program runs with the module it brings, camel-yaml-dsl 4.23.0. The YAML route below decides on the order amount, calls a Spring bean, uses a property and then sends to a Java route. A second start loads a file with one misspelt key:

Java
package demo.camel.yaml;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.Route;
import org.apache.camel.builder.RouteBuilder;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

@SpringBootApplication
public class YamlRoutes {

    // called from the YAML route by its bean name
    @Service("orderService")
    static class OrderService {
        public String label(int amount) {
            return "small order of " + amount;
        }
    }

    // a Java route that the YAML route sends to
    @Component
    static class AuditRoute extends RouteBuilder {
        @Override
        public void configure() {
            from("direct:audit").routeId("audit").setBody(simple("audited: ${body}"));
        }
    }

    public static void main(String[] args) throws Exception {
        try (InputStream in = YamlRoutes.class.getResourceAsStream("/routes/orders.yaml")) {
            System.out.println("classpath:routes/orders.yaml");
            System.out.print(new String(in.readAllBytes(), StandardCharsets.UTF_8));
        }
        System.out.println();

        try (ConfigurableApplicationContext spring = start("classpath:routes/*.yaml")) {
            CamelContext camel = spring.getBean(CamelContext.class);
            for (Route route : camel.getRoutes()) {
                System.out.println("route " + route.getRouteId() + " from "
                        + route.getEndpoint().getEndpointUri() + ", source "
                        + route.getSourceLocationShort());
            }
            ProducerTemplate template = spring.getBean(ProducerTemplate.class);
            for (int amount : new int[] {250, 40}) {
                System.out.println("direct:order with " + amount + " -> "
                        + template.requestBody("direct:order", amount, String.class));
            }
        }

        System.out.println();
        try (ConfigurableApplicationContext spring = start("classpath:broken-routes/*.yaml")) {
            System.out.println("started with " + spring.getBean(CamelContext.class)
                    .getRoutes().size() + " routes");
        } catch (Exception e) {
            Throwable cause = e;
            while (cause.getCause() != null) {
                cause = cause.getCause();
            }
            System.out.println("startup failed: " + e.getClass().getSimpleName());
            System.out.println("root cause: " + cause.getClass().getSimpleName() + ": "
                    + cause.getMessage().lines().findFirst().orElse(""));
        }
    }

    static ConfigurableApplicationContext start(String routesPattern) {
        SpringApplication app = new SpringApplication(YamlRoutes.class);
        Map<String, Object> props = new HashMap<>(Map.of(
                // the programs on this page share a classpath that includes Tomcat
                "spring.main.web-application-type", "none",
                "camel.main.routes-include-pattern", routesPattern,
                "camel.main.source-location-enabled", "true",
                "shop.currency", "EUR",
                "spring.main.banner-mode", "off",
                "logging.level.root", "OFF"));
        app.setDefaultProperties(props);
        return app.run();
    }
}
Output
classpath:routes/orders.yaml
- route:
    id: orders
    from:
      uri: direct:order
      steps:
        - choice:
            when:
              - simple: "${body} > 100"
                steps:
                  - setBody:
                      simple: "large order of ${body} {{shop.currency}}"
            otherwise:
              steps:
                - bean:
                    ref: orderService
                    method: label
        - to: direct:audit

route audit from direct://audit, source YamlRoutes:33
route orders from direct://order, source orders.yaml:4
direct:order with 250 -> audited: large order of 250 EUR
direct:order with 40 -> audited: small order of 40

startup failed: CamelSpringBootInitializationException
root cause: UnknownNodeIdException: Unknown node id: setbody
  • The program prints the YAML file first. Each list item is a route; from holds the endpoint and the steps, and every step has the same name as its Java DSL method: choice, setBody, bean, to.
  • Both routes ended up in the same CamelContext: audit from the @Component class and orders from the file. Camel recorded where each route was defined: line 4 of orders.yaml, the from line, and line 33 of YamlRoutes. YAML routes always carry their file and line; for Java routes it needs camel.main.source-location-enabled=true, and without it their source is null.
  • Order 250 took the when branch. {{shop.currency}} was resolved from Spring's properties, exactly as in a Java route, giving large order of 250 EUR.
  • Order 40 took otherwise and called the orderService bean by its Spring bean name with ref and method.
  • Both replies start with audited:, so the YAML route's to: direct:audit reached the Java route. Routes in different formats call each other through endpoints, as Java routes do.
  • The second start used a file with setbody instead of setBody. The application did not start: it failed with CamelSpringBootInitializationException, caused by UnknownNodeIdException: Unknown node id: setbody. YAML keys are case-sensitive, and the parser rejects unknown steps at startup, so a typo in a route file stops the deployment.

The program sets camel.main.routes-include-pattern to its own folder, classpath:routes/*.yaml, because the programs on this page share one classpath. In an application, putting the files in src/main/resources/camel/ needs no setting at all. A pattern that matches no file is not an error: the application starts with only its Java routes, so check the route list at startup when the files are new. Placeholders, beans and components work the same way in YAML routes, and the Camel introduction shows the same routing ideas in Java.

Configuring components with properties

Every component option can be set for the whole application as a property. The seda component's queue size is easy to check, because a full queue refuses new messages. The program starts the application twice: once with the property spelled correctly, and once with a typo:

Java
package demo.camel.config;

import java.util.HashMap;
import java.util.Map;
import org.apache.camel.CamelContext;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.component.seda.SedaEndpoint;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ComponentConfig {

    public static void main(String[] args) {
        System.out.println("1. camel.component.seda.queue-size=2");
        run(Map.of("camel.component.seda.queue-size", "2"));
        System.out.println("2. a misspelt option: camel.component.seda.queue-sise=2");
        run(Map.of("camel.component.seda.queue-sise", "2"));
    }

    static void run(Map<String, Object> extra) {
        Map<String, Object> properties = new HashMap<>(extra);
        properties.put("spring.main.web-application-type", "none"); // no web server
        properties.put("spring.main.banner-mode", "off");
        properties.put("logging.level.root", "OFF");
        SpringApplication app = new SpringApplication(ComponentConfig.class);
        app.setDefaultProperties(properties);
        try (var spring = app.run()) {
            ProducerTemplate template = spring.getBean(ProducerTemplate.class);
            SedaEndpoint queue = spring.getBean(CamelContext.class)
                    .getEndpoint("seda:work", SedaEndpoint.class);
            System.out.println("  seda:work size = " + queue.getSize());
            for (int i = 1; i <= 3; i++) {
                try {
                    template.sendBody("seda:work", "job " + i);
                    System.out.println("  job " + i + " queued");
                } catch (Exception e) {
                    System.out.println("  job " + i + " refused: " + e.getCause().getMessage());
                }
            }
        } catch (Exception e) {
            Throwable root = e;
            while (root.getCause() != null) {
                root = root.getCause();
            }
            System.out.println("  startup failed: " + root.getMessage()
                    .lines().findFirst().orElse(""));
        }
    }
}
Output
1. camel.component.seda.queue-size=2
  seda:work size = 2
  job 1 queued
  job 2 queued
  job 3 refused: Queue full
2. a misspelt option: camel.component.seda.queue-sise=2
  seda:work size = 1000
  job 1 queued
  job 2 queued
  job 3 queued
  • With camel.component.seda.queue-size=2, the endpoint seda:work had size 2. Nothing consumed from it, so jobs 1 and 2 filled it and job 3 was refused with Queue full.
  • With the typo queue-sise, the application started normally, and the queue had its default size of 1000. The property was ignored without an error, and all three jobs were queued.

An IDE with Spring Boot support flags unknown properties using the configuration metadata that every Camel starter ships, which catches such typos while typing. Property names use the kebab-case form of the option name: the option queueSize becomes queue-size. Options set in an endpoint URI, such as seda:work?size=10, override the component setting for that endpoint.

Frequently used camel.main properties in Camel 4.23
PropertyDefaultEffect
camel.main.nameGeneratedName of the CamelContext
camel.main.run-controllerfalseKeep the JVM running without a web server
camel.main.stream-caching-enabledtrueCache stream bodies so they can be read more than once
camel.main.message-historyfalseRecord the route steps of each exchange
camel.main.shutdown-timeout45Seconds to wait for in-flight exchanges at shutdown
camel.main.routes-include-patternclasspath:camel/*,...Where route files are loaded from

Older Camel Spring Boot releases used the prefix camel.springboot.* for most of these settings; they now live under camel.main.*.

Keeping an application without a web server running

A Spring Boot application with no web server ends when main returns, because nothing else keeps the JVM alive. For a Camel application that only runs timer, file or queue routes, that means it exits right after starting: a heartbeat route started without any extra setting printed nothing, because the JVM ended before the first tick. With camel.main.run-controller=true, Camel starts a non-daemon thread that keeps the JVM running until the application is stopped:

Java
package demo.camel.keeprunning;

import java.util.Map;
import org.apache.camel.builder.RouteBuilder;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.stereotype.Component;

@SpringBootApplication
public class KeepRunning {

    @Component
    static class Heartbeat extends RouteBuilder {
        @Override
        public void configure() {
            from("timer:heartbeat?period=200&includeMetadata=true").routeId("heartbeat")
                    .process(e -> System.out.println("  heartbeat "
                            + e.getProperty("CamelTimerCounter")
                            + " on thread " + Thread.currentThread().getName()
                                    .replaceAll(".*thread #\\d+ - ", "")));
        }
    }

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(KeepRunning.class);
        app.setDefaultProperties(Map.of(
                "spring.main.web-application-type", "none", // nothing else keeps it alive
                "camel.main.run-controller", "true",
                "camel.main.duration-max-messages", "3",
                "spring.main.banner-mode", "off",
                "logging.level.root", "OFF"));
        app.addListeners((ContextClosedEvent event) -> System.out.println(
                "Spring context closed by the run controller"));
        app.run(args);
        System.out.println("main thread: run() returned, the JVM keeps running");
    }
}
Output
main thread: run() returned, the JVM keeps running
  heartbeat 1 on thread timer://heartbeat
  heartbeat 2 on thread timer://heartbeat
  heartbeat 3 on thread timer://heartbeat
Spring context closed by the run controller
  • run() returned at once and the main thread ended, but the JVM kept running because of the run controller.
  • The timer fired three times, on its own thread. The counter came from the CamelTimerCounter exchange property, which the timer sets only with includeMetadata=true.
  • camel.main.duration-max-messages=3 told the run controller to stop after three messages, and it closed the Spring context. Without it, the application runs until it is stopped from outside, which is what a service wants; the duration settings are mainly for demos and batch-style jobs.

An application with the web or WebFlux starter does not need the run controller: the web server's threads keep it alive. In Camel 4.14 the property was renamed from camel.main.main-run-controller, which still works but is deprecated.

REST routes and Spring MVC in one application, with health

With camel-servlet-starter and the web starter, REST DSL routes are served by Spring Boot's Tomcat through CamelServlet, next to ordinary Spring MVC controllers. Actuator's health endpoint then includes Camel. This program starts on a random port, calls a controller and a REST route, checks health, stops the route and checks health again:

Java
package demo.camel.rest;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.server.context.WebServerApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
public class RestAndMvc {

    @Component
    static class OrderApi extends RouteBuilder {
        @Override
        public void configure() {
            rest("/orders").get("/{id}").to("direct:order");
            from("direct:order").routeId("order")
                    .setBody(simple("order ${header.id} from a Camel route"));
        }
    }

    @RestController
    static class StatusController {
        @GetMapping("/status")
        String status() {
            return "up, from a Spring MVC controller";
        }
    }

    public static void main(String[] args) throws Exception {
        SpringApplication app = new SpringApplication(RestAndMvc.class);
        app.setDefaultProperties(Map.of(
                "server.port", "0",
                "management.endpoints.web.exposure.include", "health",
                "management.endpoint.health.show-components", "always",
                "spring.main.banner-mode", "off",
                "logging.level.root", "OFF"));
        try (var spring = app.run(args)) {
            int port = ((WebServerApplicationContext) spring).getWebServer().getPort();
            String base = "http://localhost:" + port;
            for (String path : new String[] {"/status", "/orders/7", "/camel/orders/7",
                "/actuator/health"}) {
                get(base, path);
            }
            spring.getBean(CamelContext.class).getRouteController().stopRoute("order");
            System.out.println("(route 'order' stopped)");
            get(base, "/actuator/health");
        }
    }

    static void get(String base, String path) throws Exception {
        HttpResponse<String> response = HttpClient.newHttpClient().send(
                HttpRequest.newBuilder(URI.create(base + path)).build(),
                HttpResponse.BodyHandlers.ofString());
        String body = response.body();
        if (path.startsWith("/actuator")) {
            // keep the overall status and the Camel components of the health report
            Matcher m = Pattern.compile("\"(camel\\w+)\":\\{\"status\":\"(\\w+)\"")
                    .matcher(body);
            StringBuilder camel = new StringBuilder();
            while (m.find()) {
                camel.append(" ").append(m.group(1)).append("=").append(m.group(2));
            }
            Matcher overall = Pattern.compile("\"status\":\"(\\w+)\"\\}$").matcher(body);
            body = "status=" + (overall.find() ? overall.group(1) : "?") + "," + camel;
        } else if (response.statusCode() == 404) {
            body = "(Spring Boot's JSON error page)";
        }
        System.out.println("GET " + path + " -> " + response.statusCode() + ": " + body);
    }
}
Output
GET /status -> 200: up, from a Spring MVC controller
GET /orders/7 -> 404: (Spring Boot's JSON error page)
GET /camel/orders/7 -> 200: order 7 from a Camel route
GET /actuator/health -> 200: status=UP, camelHealth=UP camelLivenessState=UP camelReadinessState=UP
(route 'order' stopped)
GET /actuator/health -> 503: status=DOWN, camelHealth=DOWN camelLivenessState=UP camelReadinessState=OUT_OF_SERVICE
  • /status was answered by the @RestController, as in any Spring Boot application.
  • /orders/7 got 404 from Spring Boot. The REST route lives under the servlet's mapping, /camel/* by default (camel.servlet.mapping.context-path), so the working URL was /camel/orders/7.
  • /actuator/health was UP, with three Camel components: camelHealth, camelLivenessState and camelReadinessState. The program prints only those and the overall status.
  • After the route was stopped, health turned DOWN with status 503. Camel's readiness became OUT_OF_SERVICE while liveness stayed UP, so a Kubernetes readiness probe would stop sending traffic to the instance, and the liveness probe would not restart it.

Setting camel.servlet.mapping.context-path=/* serves REST routes at the root, but then the servlet competes with Spring MVC for every path. A separate prefix, such as /api/*, keeps the two apart. The Camel REST DSL page covers the REST DSL itself, and the Spring Boot Actuator page covers health endpoints.

Testing routes with @CamelSpringBootTest

Route tests should not need the real systems a route talks to. camel-test-spring-junit5 starts the Spring Boot application in a test and lets the test replace endpoints before the routes start. This order route calls an HTTP fraud check for orders over 100 and then sends to Kafka; the test replaces both with mock endpoints. The program runs the JUnit 6 test class with the JUnit Platform launcher and prints the summary, and the second test contains a wrong expectation on purpose:

Java
package demo.camel.test;

import static org.junit.platform.engine.discovery.DiscoverySelectors.selectClass;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import org.apache.camel.CamelContext;
import org.apache.camel.EndpointInject;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.AdviceWith;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.spring.junit5.CamelSpringBootTest;
import org.apache.camel.test.spring.junit5.UseAdviceWith;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder;
import org.junit.platform.launcher.core.LauncherFactory;
import org.junit.platform.launcher.listeners.SummaryGeneratingListener;
import org.junit.platform.launcher.listeners.TestExecutionSummary;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.stereotype.Component;

public class RouteTest {

    @SpringBootApplication
    static class ShopApp {
        @Component
        static class OrderRoute extends RouteBuilder {
            @Override
            public void configure() {
                from("direct:order").routeId("order")
                        .choice()
                            .when(simple("${body} > 100")).to("http://fraud-check.internal/score")
                        .end()
                        .to("kafka:orders");
            }
        }
    }

    @CamelSpringBootTest
    @SpringBootTest(classes = ShopApp.class,
            properties = {"logging.level.root=OFF", "spring.main.banner-mode=off"})
    @UseAdviceWith
    @TestMethodOrder(MethodOrderer.OrderAnnotation.class)
    static class OrderRouteTest {
        @Autowired
        CamelContext context;

        @Autowired
        ProducerTemplate template;

        @EndpointInject("mock:fraud")
        MockEndpoint fraud;

        @EndpointInject("mock:kafka")
        MockEndpoint kafka;

        // the Spring context, and so the CamelContext, is shared by both tests
        void adviseOnce() throws Exception {
            if (!context.isStarted()) {
                // replace the real endpoints before the route starts
                AdviceWith.adviceWith(context, "order", route -> {
                    route.weaveByToUri("http*").replace().to("mock:fraud");
                    route.weaveByToUri("kafka*").replace().to("mock:kafka");
                });
                context.start();
            }
        }

        @BeforeEach
        void resetMocks() {
            // mock endpoints keep their messages and expectations between tests
            MockEndpoint.resetMocks(context);
        }

        @Test
        @Order(1)
        void bigOrdersGoThroughTheFraudCheck() throws Exception {
            adviseOnce();

            fraud.expectedBodiesReceived(250);
            kafka.expectedBodiesReceived(40, 250);
            template.sendBody("direct:order", 40);
            template.sendBody("direct:order", 250);
            MockEndpoint.assertIsSatisfied(context);
        }

        @Test
        @Order(2)
        void smallOrdersSkipTheFraudCheck() throws Exception {
            adviseOnce();

            fraud.expectedMessageCount(1); // wrong on purpose: should be 0
            template.sendBody("direct:order", 40);
            MockEndpoint.assertIsSatisfied(context);
        }
    }

    public static void main(String[] args) {
        // quiet the test listeners that log before Spring Boot configures logging
        ((Logger) LoggerFactory.getLogger("ROOT")).setLevel(Level.OFF);
        SummaryGeneratingListener listener = new SummaryGeneratingListener();
        LauncherFactory.create().execute(LauncherDiscoveryRequestBuilder.request()
                .selectors(selectClass(OrderRouteTest.class)).build(), listener);
        TestExecutionSummary summary = listener.getSummary();
        System.out.println("tests found " + summary.getTestsFoundCount()
                + ", succeeded " + summary.getTestsSucceededCount()
                + ", failed " + summary.getTestsFailedCount());
        summary.getFailures().forEach(f -> System.out.println("FAILED "
                + f.getTestIdentifier().getDisplayName() + ": "
                + f.getException().getMessage()));
    }
}
Output
tests found 2, succeeded 1, failed 1
FAILED smallOrdersSkipTheFraudCheck(): mock://fraud Received message count. Expected: <1> but was: <0>
  • The first test passed: order 250 went through mock:fraud, and both orders reached mock:kafka in the order sent.
  • The second test failed with mock://fraud Received message count. Expected: <1> but was: <0>: an order of 40 skips the fraud check, so the expectation of one message was wrong. The message names the endpoint, the expected value and the actual one.
  • @UseAdviceWith keeps the CamelContext from starting, so that AdviceWith.adviceWith can replace the http and kafka endpoints first. The test classpath has neither camel-http nor camel-kafka, and the route never needed them.

Spring caches the application context between tests, so both tests share one CamelContext. That is why the advice runs only once, and why the mocks are reset in @BeforeEach. Without MockEndpoint.resetMocks, the second test also saw the first test's messages and expectations, and failed with mock://kafka Received message count. Expected: <2> but was: <3> instead of its own error. The Camel testing page covers mocks, AdviceWith and NotifyBuilder in detail.

Choosing how to set up Camel in Spring Boot

Common situations and what fits them
SituationWhat to use
Routes in JavaRouteBuilder classes annotated with @Component
Routes edited outside Java codeYAML files in src/main/resources/camel/ with camel-yaml-dsl-starter
Calling application code from a route.bean("beanName", "method") on a Spring bean
Configuration per environment{{some.key}} placeholders and camel.component.* properties in profile files
A service with only timer, file or queue routescamel.main.run-controller=true
REST APIs next to Spring MVCcamel-servlet-starter with its own context path
Kubernetes probesActuator health with Camel's liveness and readiness
Route tests@CamelSpringBootTest, @UseAdviceWith, mock endpoints reset before each test
Metricscamel-micrometer-starter, as on the Camel Micrometer page

The traps to remember are misspelt camel.component.* properties that are silently ignored, applications that exit at once without a web server or run controller, REST routes that live under /camel/*, and mock endpoints that keep state between tests. For the basics of routes and exchanges, see the Camel introduction.