36.4. 직접 유형 구현
36.4.1. 개요
일반적으로 유형 변환기를 구현하는 권장 방법은 이전 섹션 36.3절. “주석을 사용하여 유형 구현” 에 설명된 대로 주석이 달린 클래스를 사용하는 것입니다. 그러나 형식 변환기의 등록을 완전히 제어하려면 사용자 지정 슬레이브 유형 변환기를 구현하고 여기에 설명된 대로 형식 변환기 레지스트리에 직접 추가할 수 있습니다.
36.4.2. TypeConverter 인터페이스 구현
고유한 형식 변환기 클래스를 구현하려면 TypeConverter
인터페이스를 구현하는 클래스를 정의합니다. 예를 들어 다음
클래스는 정수 값을 MyOrder
TypeConverterMyOrder
개체로 변환합니다. 여기서 정수 값은 MyOrder 개체의 순서 ID를 초기화하는 데 사용됩니다.
import org.apache.camel.TypeConverter private class MyOrderTypeConverter implements TypeConverter { public <T> T convertTo(Class<T> type, Object value) { // converter from value to the MyOrder bean MyOrder order = new MyOrder(); order.setId(Integer.parseInt(value.toString())); return (T) order; } public <T> T convertTo(Class<T> type, Exchange exchange, Object value) { // this method with the Exchange parameter will be preferd by Camel to invoke // this allows you to fetch information from the exchange during convertions // such as an encoding parameter or the likes return convertTo(type, value); } public <T> T mandatoryConvertTo(Class<T> type, Object value) { return convertTo(type, value); } public <T> T mandatoryConvertTo(Class<T> type, Exchange exchange, Object value) { return convertTo(type, value); } }
import org.apache.camel.TypeConverter
private class MyOrderTypeConverter implements TypeConverter {
public <T> T convertTo(Class<T> type, Object value) {
// converter from value to the MyOrder bean
MyOrder order = new MyOrder();
order.setId(Integer.parseInt(value.toString()));
return (T) order;
}
public <T> T convertTo(Class<T> type, Exchange exchange, Object value) {
// this method with the Exchange parameter will be preferd by Camel to invoke
// this allows you to fetch information from the exchange during convertions
// such as an encoding parameter or the likes
return convertTo(type, value);
}
public <T> T mandatoryConvertTo(Class<T> type, Object value) {
return convertTo(type, value);
}
public <T> T mandatoryConvertTo(Class<T> type, Exchange exchange, Object value) {
return convertTo(type, value);
}
}
36.4.3. 레지스트리에 유형 변환기 추가
다음과 같은 코드를 사용하여 형식 변환기 레지스트리에 사용자 정의 유형 변환기를 직접 추가할 수 있습니다.
// Add the custom type converter to the type converter registry context.getTypeConverterRegistry().addTypeConverter(MyOrder.class, String.class, new MyOrderTypeConverter());
// Add the custom type converter to the type converter registry
context.getTypeConverterRegistry().addTypeConverter(MyOrder.class, String.class, new MyOrderTypeConverter());
여기서 context
는 현재 org.apache.camel.CamelContext
인스턴스입니다. addTypeConverter()
메서드는 String.class
에서 MyOrder.class
로 특정 형식 변환에 대해 MyOrderTypeConverter
클래스를 등록합니다.
META-INF
파일을 사용하지 않고도 Camel 애플리케이션에 사용자 정의 유형 변환기를 추가할 수 있습니다. Spring 또는 블루프린트 를 사용하는 경우 <bean>을 선언하면 됩니다. CamelContext에서 빈을 자동으로 검색하고 변환기를 추가합니다.
<bean id="myOrderTypeConverters" class="..."/> <camelContext> ... </camelContext>
<bean id="myOrderTypeConverters" class="..."/>
<camelContext>
...
</camelContext>
클래스가 더 많은 경우 여러 <bean>s를 선언할 수 있습니다.