【问题标题】:How to support Backward Comparability for the type of param in REST APIs如何支持 REST API 中参数类型的向后可比性
【发布时间】:2018-09-11 10:16:11
【问题描述】:

我有 40-45 个使用 Apache CXF 框架构建的 REST API。我确实有一个参数为telehpneNumber,它的类型为Long,现在我需要将其更改为String,但也希望这些应该向后兼容。

目前的想法是创建两个像 v1(old) v2(new) v2 will be acceptingStringformat. Using adaptor pattern I'll proxyv1request tov2. ButtelephoneNumberparam is used in various objects & places. I though of making it as a type ofObject` 这样的休息控制器,但是当它是关于接受请求时,它按预期工作,但是当我返回响应时它不会。

解决这种向后兼容问题的正确方法是什么?

目前我的想法类似于下面的代码:

class OldTelephoneRequest{
    Long telephoneNumber;
    //some more variables
    //getters & setters

}

class TelephoneRequest{
    String telephoneNumber;
    //some more variables
    //getters & setters

}

@Path("/rest/services/v1")
class OldRestAPI{


    @Path("telephoneDetails")
    public Response telephoneDetails(OldTelephoneRequest oldTelephoneRequest){
        //make proxy call to v2 which will accept telephoneRequst object
        //Convert telephoneRequst to newTelephoneRequst(which will have telephoneNumber as String )
        TelephoneRequest request=new TelephoneRequest(oldTelephoneRequest);

        return RestAPI.telephoneDetails(telephoneRequest)
    }
}



@Path("/rest/services/v2")
class RestAPI{


    @Path("telephoneDetails")
    public Response telephoneDetails(TelephoneRequest telephoneRequest){
        //business logic
    }
}

上述方法的问题是我必须为每个请求构建 40-45 个构造函数,这些构造函数基本上将从 oldRequest 转换为 newRequst 让我知道解决这个问题的更好方法是什么。

【问题讨论】:

    标签: java rest jackson cxf backwards-compatibility


    【解决方案1】:

    最简洁的解决方案是让设计保持原样,让 MapStruct 为您进行映射:

    @Mapper
    public interface TelephoneRequestMapper {
    
        TelephoneRequestMapper INSTANCE = Mappers.getMapper(TelephoneRequestMapper.class );
    
        @Mapping(source = "oldTelephoneRequest", target = "telephoneRequest")
        TelephoneRequest oldTelephoneRequestToTelephoneRequest(OldTelephoneRequest oldTelephoneRequest); 
    }
    

    更多信息: http://mapstruct.org/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-02
      相关资源
      最近更新 更多