2.5. Creating Exchange Instances
When processing messages with Java code (for example, in a bean class or in a processor class), it is often necessary to create a fresh exchange instance. If you need to create an
Exchangeobject, the easiest approach is to invoke the methods of the
ExchangeBuilderclass, as described here.
The fully qualified name of the
ExchangeBuilderclass is as follows:
ExchangeBuilderexposes the static method,
anExchange, which you can use to start building an exchange object.
For example, the following code creates a new exchange object containing the message body string,
Hello World!, and with headers containing username and password credentials:
// Java import org.apache.camel.Exchange; import org.apache.camel.builder.ExchangeBuilder; ... Exchange exch = ExchangeBuilder.anExchange(camelCtx) .withBody("Hello World!") .withHeader("username", "jdoe") .withHeader("password", "pass") .build();
ExchangeBuilderclass supports the following methods:
ExchangeBuilder anExchange(CamelContext context)
- (static method) Initiate building an exchange object.
- Build the exchange.
ExchangeBuilder withBody(Object body)
- Set the message body on the exchange (that is, sets the exchange's In message body).
ExchangeBuilder withHeader(String key, Object value)
- Set a header on the exchange (that is, sets a header on the exchange's In message).
ExchangeBuilder withPattern(ExchangePattern pattern)
- Sets the exchange pattern on the exchange.
ExchangeBuilder withProperty(String key, Object value)
- Sets a property on the exchange.