276.6. REST producer 绑定
REST 生成者支持使用 JSon 或 XML (如 rest-dsl)进行绑定。
例如,要使用打开 json 绑定模式的 jetty,您可以在 rest 配置中配置它:
restConfiguration().component("jetty").host("localhost").port(8080).bindingMode(RestBindingMode.json); from("direct:start") .to("rest:post:user");
然后,在使用 rest producer 调用 REST 服务时,它将在调用 REST 服务前自动将任何 POJO 绑定到 json :
UserPojo user = new UserPojo(); user.setId(123); user.setName("Donald Duck"); template.sendBody("direct:start", user);
在上例中,我们发送了一个 POJO 实例 UserPojo
作为消息正文。由于我们在其它配置中开启了 JSon 绑定,因此 POJO 将在调用 REST 服务前从 POJO 总结到 JSon。
但是,如果您想要为响应消息执行绑定(例如 REST 服务发回为响应),则需要配置 outType
选项,以指定 POJO 的类名称(从 JSon 变为 POJO)到 POJO。
例如,如果 REST 服务返回绑定到 com.foo.MyResponsePojo
的 JSon 有效负载,您可以将其配置为:
restConfiguration().component("jetty").host("localhost").port(8080).bindingMode(RestBindingMode.json); from("direct:start") .to("rest:post:user?outType=com.foo.MyResponsePojo");
重要
如果您希望为从调用 REST 服务收到的响应消息进行 POJO 绑定,您必须配置 outType
选项。