在REST API中添加标题会破坏向后兼容性

问题描述 投票:0回答:1

我有一个REST接口定义如下

public interface UserService {

    @GZIP
    @POST
    Response createUser(@HeaderParam("hostName") String hostName, User user);

}

我想再读两个头addToCacheuseCache 。 显而易见的解决方案是在上述签名中添加标头。

尽管这对于在其余客户端上进行显式HTTP调用是可行的,但修改接口签名会破坏功能测试代码库的向后兼容性,该功能测试代码库已使用REST代理服务连接到上述服务。

我看到的唯一出路是在User对象中传递两个参数。 还有其他出路吗?

rest jax-rs resteasy
1个回答
1
投票

您可以将标头参数作为实现类中的字段注入:

public interface UserService {
    Response createUser(String hostName, User user);
}

@Path("/userservice")
public class UserServiceRestImpl implements UserService{

    @HeaderParam("addToCache")
    private String addToCache;

    @HeaderParam("useCache")
    private String useCache;

    @GZIP
    @POST
    Response createUser(@HeaderParam("hostName") String hostName, User user){
        System.out.println(addToCache);
        System.out.println(useCache);
    }
}

更新:尝试禁用自动扫描并明确指定资源:

<!-- disabled auto scanning
<context-param>
    <param-name>resteasy.scan</param-name>
    <param-value>true</param-value>
</context-param>
        -->
<context-param>
    <param-name>resteasy.resources</param-name>
    <param-value>com.yourpackage.UserServiceRestImpl</param-value>
</context-param>

UPDATED2:您也可以尝试注入@Context HttpHeaders而不是@HeaderParam:

private @Context HttpHeaders headers;

...

String addToCache = headers.getHeaderString("addToCache");
© www.soinside.com 2019 - 2024. All rights reserved.