Switch

The Switch EIP is an optimized Content Based Router which selects a single branch (when/otherwise) during startup, and always executes the same branch. This allows to optimize the runtime Camel to avoid this evaluation process for every message; because they are supposed to always be routed on the same branch.

Because the Switch EIP evaluates the predicates during startup, then the predicates cannot be based on the content of the message. Therefore, the predicates would often be based on property placeholders, JVM system properties, or OS Environment variables.

The Switch EIP combined with Route Templates allows for more flexible templates, as the template parameters can be used as the predicates in the Switch EIP; meaning that the Switch EIP is fully parameterized, but is optimized for best runtime performance.

image

Switch options

The Switch eip supports 2 options, which are listed below.

Name Description Default Type

when

List

otherwise

Sets the otherwise node.

OtherwiseDefinition

description

Sets the description of this node.

DescriptionDefinition

Example

The Camel Simple language is great to use with the Switch EIP to select a specific branch based on property placeholders.

Here we select from the Switch the first predicate that matches. So if there is a property placeholder with the key foo then its select, and so on. Notice how we can use {{?foo}} to mark the property placeholder as optional.

from("direct:a")
    .doSwitch()
        .when(simple("{{?foo}}")).to("direct:foo")
        .when(simple("{{?bar}}")).to("direct:bar")
        .otherwise().to("direct:other");

And the same example using XML DSL:

<route>
    <from uri="direct:a"/>
    <doSwitch>
        <when>
            <simple>{{?foo}}</simple>
            <to uri="direct:foo"/>
        </when>
        <when>
            <simple>{{?bar}}</simple>
            <to uri="direct:bar"/>
        </when>
        <otherwise>
            <to uri="direct:other"/>
        </otherwise>
    </doSwitch>
</route>

And in YAML DS:

- from:
    uri: "direct:a"
    steps:
      - doSwitch:
          when:
            - simple: "{{?foo}}"
              steps:
                - to: "direct:foo"
            - simple: "{{?bar}}"
              steps:
                - to: "direct:bar"
          otherwise:
            steps:
              - to: "direct:other"
Otherwise, is optional, and if none of the predicates would match, then no branches is selected.

Why can I not use otherwise in Java DSL

See the same section at Choice EIP.