MuleESB / Apache Camel Interview Questions
How does the Camel Type Converter work and how do you register a custom type converter?
The Type Converter framework automatically converts a value from its current type to a requested target type. Every call to exchange.getIn().getBody(TargetClass.class) goes through the TypeConverterRegistry, which holds a lookup table of registered converters. Camel ships with hundreds of built-in converters (byte[] to String, InputStream to byte[], String to Integer, etc.).
To register a custom type converter, create a class annotated with @Converter(generateLoader=true) and annotate each conversion method with @Converter. Camel uses annotation processing at build time to generate the loader class, which is registered automatically via META-INF/services.
@Converter(generateLoader = true)
public final class OrderConverters {
@Converter
public static Order toOrder(String json, Exchange exchange) {
ObjectMapper om = exchange.getContext()
.getRegistry().lookupByNameAndType("objectMapper", ObjectMapper.class);
return om.readValue(json, Order.class);
}
@Converter
public static String fromOrder(Order order) {
return order.getId() + ":" + order.getAmount();
}
}
// Automatic use in route:
from("direct:in")
.process(e -> {
Order order = e.getIn().getBody(Order.class); // triggers custom converter
System.out.println(order.getId());
});The converter method signature supports optional second parameters of type Exchange or CamelContext for access to context. The converter is looked up by (from-type, to-type) pair. If no direct converter exists, Camel attempts multi-step conversion through intermediate types. Register converters programmatically via context.getTypeConverterRegistry().addTypeConverter(toType, fromType, converter) for dynamic registration.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
