17.5. 使用 Java DSL
下一步会实例化与此记录类型关联的 DataFormat bindy 类,并提供一个类作为参数。
例如,以下命令使用类 BindyCsvDataFormat
(对应于与 CSV 记录类型关联的类),它使用 com.acme.model.MyModel.class 来初始化这个软件包中配置的模型对象。
DataFormat bindy = new BindyCsvDataFormat(com.acme.model.MyModel.class);
DataFormat bindy = new BindyCsvDataFormat(com.acme.model.MyModel.class);
17.5.1. 设置区域设置 复制链接链接已复制到粘贴板!
bindy 支持在 dataformat 中配置区域设置,例如
BindyCsvDataFormat bindy = new BindyCsvDataFormat(com.acme.model.MyModel.class); bindy.setLocale("us");
BindyCsvDataFormat bindy = new BindyCsvDataFormat(com.acme.model.MyModel.class);
bindy.setLocale("us");
或者要使用平台默认区域设置,然后使用 "default" 作为区域设置名称。
BindyCsvDataFormat bindy = new BindyCsvDataFormat(com.acme.model.MyModel.class); bindy.setLocale("default");
BindyCsvDataFormat bindy = new BindyCsvDataFormat(com.acme.model.MyModel.class);
bindy.setLocale("default");
17.5.2. Unmarshaling 复制链接链接已复制到粘贴板!
from("file://inbox") .unmarshal(bindy) .to("direct:handleOrders");
from("file://inbox")
.unmarshal(bindy)
.to("direct:handleOrders");
另外,您可以使用命名引用到数据格式,然后在 Registry 中定义,如 Spring XML 文件:
from("file://inbox") .unmarshal("myBindyDataFormat") .to("direct:handleOrders");
from("file://inbox")
.unmarshal("myBindyDataFormat")
.to("direct:handleOrders");
Camel 路由将获取 inbox 目录中的文件,unmarshall CSV 记录成模型对象的集合,并将集合
发送到 handleOrders
引用的路由。
返回的集合是 Map 对象列表。列表中的每个映射都包含 CSV 每行的模型对象。其后面的原因是 每行都与多个对象对应。当您只期望每行返回一个对象时,这可能会造成混淆。
每个对象可以使用其类名称来检索。
假设您要从此映射中提取单个 Order 对象以便在路由中处理,您可以使用 Splitter 和 Processor 的组合,如下所示:
注意 Bindy 使用 CHARSET_NAME 属性或 CHARSET_NAME 标头的事实,如 Exchange 接口中定义,以执行为 unmarshalling 接收的输入流的字符集转换。在一些制作者(如 file-endpoint)中,您可以定义一个字符集。characterset 转换可由此制作者完成。有时,您需要在将此属性发送到 unmarshal 之前从交换中删除此属性或标头。如果您没有删除它,则转换过程可能会进行两次,这可能会导致不必要的结果。
from("file://inbox?charset=Cp922") .removeProperty(Exchange.CHARSET_NAME) .unmarshal("myBindyDataFormat") .to("direct:handleOrders");
from("file://inbox?charset=Cp922")
.removeProperty(Exchange.CHARSET_NAME)
.unmarshal("myBindyDataFormat")
.to("direct:handleOrders");
17.5.3. marshaling 复制链接链接已复制到粘贴板!
要从模型对象集合生成 CSV 记录,请创建以下路由:
from("direct:handleOrders") .marshal(bindy) .to("file://outbox")
from("direct:handleOrders")
.marshal(bindy)
.to("file://outbox")