gpt4 book ai didi

java - 如何在使用 Jersey 时在界面上注释 JAX-RS

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:37:07 24 4
gpt4 key购买 nike

这个问题已经被问过几次了before ,但是答案似乎不起作用和/或 Jersey 已经进行了更多更改。

我正在使用 JAX-RS 和 Jersey(版本 2.24)公开一些 REST API。我希望用 JAX-RS 和具体实现(没有任何注释)来注释接口(interface)。然而,由于 this patch Jersey 停止支持这种可能性。据我了解 spec ,它并不严格禁止这样做。

If a subclass or implementation method has any JAX-RS annotations then all of the annotations on the superclass or interface method are ignored.

暗示这样做是完全可以的。在许多情况下,最好使用一个接口(interface),让服务器和客户端各有各自的实现。

有很多解决方案,

  1. 使用 ResourceConfig 并执行 registerClasses(MyImplementation.class) 。但是,这不起作用。
  2. web.xml 中禁用包扫描配置,创建一个自定义的 javax.ws.rs.Application 并为您的 register从那里实现。不起作用。
  3. 使用ResourceConfig 并定义自定义AbstractBinder 并执行bind 以便Jersey 的依赖注入(inject)可以找到具体的实现。不起作用。
  4. 使用 RESTEasy。 RESTEasy 似乎没有像 Jersey 那样强加接口(interface)限制。我自己从未尝试过。

如果有人可以分享他们的经验,我将不胜感激。任何关于如何让 Jersey 工作的帮助也会很棒。至于选项(4)是否真的需要切换?下面的示例代码。

我的资源

 package com.foo;

import javax.ws.rs.GET;
import javax.ws.rs.Path;


@Path("/hello")
public interface MyResource {

@GET
public String sayHello();

}

MyResourceImpl

package com.bar;

public class MyResourceImpl implements MyResource {

@Override
public String sayHello() {
return "Hello Jersey";
}
}

还有一个 web.xml 启用了包扫描以扫描 com.foo

最佳答案

如果您想将资源接口(interface)与实现分开(允许您将接口(interface)与一些 REST 客户端(如 resteasy 客户端)一起使用),您可以在实现上使用 @RequestScoped。因此,这个 bean 可以使用注入(inject)的资源,如 EJB、EntityManager ......使用你的样本:

import javax.ws.rs.GET;
import javax.ws.rs.Path;

@Path("/hello")
public interface MyResource {

@GET
public String sayHello();
}

我的资源实现

package com.bar;

@RequestScoped
public class MyResourceImpl implements MyResource {

@Override
public String sayHello() {
return "Hello Jersey";
}
}

然而,您必须考虑到,一旦您在实现代码中使用特定的 JAX-RS 类(如 UriInfo、Response 对象...),您将在您的实现和 JAX-RS 之间创建一个耦合API。

关于java - 如何在使用 Jersey 时在界面上注释 JAX-RS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40877018/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com