【问题标题】:Wire concrete implementation to interface in blueprint.xml将具体实现连接到 blueprint.xml 中的接口
【发布时间】:2019-02-26 03:44:51
【问题描述】:

背景

希望将具体类连接到 blueprint.xml 中 REST 服务器的 @POST 方法的参数。

问题

Jackson 数据绑定找不到方法的send 参数的具体实现。

代码

Java

REST 服务器有一个send 方法,定义为:

public interface NotificationServer {
    @POST
    Response send(NotificationRequest notificationRequest);
}

NotificationRequest 也是一个接口:

public interface NotificationRequest {

NotificationServer的具体实现,称为EmailNotificationServerImpl,实现了接口:

public class EmailNotificationServerImpl implements NotificationServer {
    @Override
    public Response send(final NotificationRequest request) {

蓝图

blueprint.xml的相关部分包括:

<bean class="EmailNotificationServerImpl" id="emailNotificationServerImpl">...</bean>
<bean class="NotificationRequestImpl" id="notificationRequestImpl" />
<service interface="NotificationRequest" ref="notificationRequestImpl" />

异常

杰克逊错误信息:

原因:com.fasterxml.jackson.databind.JsonMappingException:无法构造 NotificationRequest 的实例:抽象类型要么需要映射到具体类型,要么具有自定义反序列化器,要么包含其他类型信息

反序列化

可以使用以下方法对类进行反序列化:

@JsonDeserialize(as = NotificationRequestImpl.class)
public interface NotificationRequest {

虽然这可行,但它并没有将实现与接口完全分离。

问题

如何在blueprint.xml 中绑定具体实现,这样@JsonDeseralize 注释就不需要了?

环境

  • Java 1.8
  • Apache Camel 2.x
  • JAX-RS 2.1
  • 杰克逊 JAX-RS JSON 提供程序 2.9.x
  • OSGi 1.2.1
  • 不使用 Spring

【问题讨论】:

    标签: java jackson apache-camel jax-rs blueprint-osgi


    【解决方案1】:

    &lt;jaxrs:providers&gt; 标记内的 JAX-RS 服务器定义中使用扩展 JacksonJsonProvider 的自定义提供程序。

    或者使用扩展StdSerializer的自定义反序列化器:

    @JsonDeserialize(using = YourDeserializer.java)
    

    或者使用多态性和@JsonTypeInfo + @JsonSubtypes 注解。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-30
      • 1970-01-01
      • 2019-10-12
      • 1970-01-01
      • 2019-12-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多