我使用Apache CXF框架构建了40-45个REST API。我有一个telehpneNumber
参数,它的类型为Long
,现在我需要将它更改为String
,但也希望这些参数应该向后兼容。
目前对它的想法是创建两个休息控制器,如v1
(旧)v2(new) v2 will be accepting
Stringformat. Using adaptor pattern I'll proxy
v1request to
v2. But
telephoneNumberparam is used in various objects & places. I though of making it as a type of
Object`,但是当它接收请求时这个工作正如预期的那样,但是当我将返回响应时它不会。
解决这种向后兼容性问题的正确方法是什么?
目前我的想法类似于下面编码的内容:
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
让我知道解决这个问题的更好方法是什么。
最干净的解决方案是保持设计不变,让MapStruct为您进行映射:
@Mapper
public interface TelephoneRequestMapper {
TelephoneRequestMapper INSTANCE = Mappers.getMapper(TelephoneRequestMapper.class );
@Mapping(source = "oldTelephoneRequest", target = "telephoneRequest")
TelephoneRequest oldTelephoneRequestToTelephoneRequest(OldTelephoneRequest oldTelephoneRequest);
}
有关更多信息:http://mapstruct.org/