Integration / 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.
More Related questions...