jakarta-ee - JAX-RS (Apache CXF) 通过 setter 进行上下文注入(inject)

标签 jakarta-ee jax-rs kotlin

我正在尝试通过 Kotlin 中的 @Context 注释将 HttpServletRequest 注入(inject)我的 JAX-RS 资源(Apache CXF 实现)。如果我通过方法参数注入(inject)它,它工作正常。但我不想用它“弄乱”我的接口(interface),所以我想通过字段/ setter 注入(inject)它。

普通字段注入(inject)的问题是代理的名称中有 $,这对于 kotlin 来说是一个问题,因为它不能使用名称中带有美元的类名。

所以我试图用这个简单的方法通过setter来做到这一点:

var req : HttpServletRequest? = null

Context
fun setRequest(req : HttpServletRequest) {
    this.req = req
}

问题是(我相信这在 Java 中也应该是一个问题),setter 是通过 org.apache.cxf.jaxrs.utils.InjectionUtils 方法中的反射调用的,该方法在引发 java.lang.IllegalArgumentException: object is not声明类的实例

我试图用谷歌搜索这个问题,但没有运气。有没有人有类似的问题或者我做错了什么?

顺便说一句,我还创建了一个 issue在 CXF 的 JIRA 中。

最佳答案

感谢评论 CXF Jira 问题的人,我设法解决了这个问题。
要使 setter 注入(inject)与 CXF 一起使用,您还必须在接口(interface)中定义 setter(不仅在实现类上)并在那里用 @Context 注释它(在接口(interface)上)。我不确定这是否真的符合规范,但似乎 CXF 需要这样。

像这样:

public MyInterface {
   @Context
   public void setRequest(HttpServletRequest req);
}

public MyClass implements MyInterface {
   private HttpServletRequest req;

   public void setRequest(HttpServletRequest req) {
      this.req = req;
   }
}

来自 CXF Jira 的 Sergey 的解释是:

This is not a standard specific issue, it is all down to the fact that the service object provided to the runtime is a proxy, and moving the setter to the interface ensures that this setter is part of the proxy. In my tests I do not have these setters on the main interface representing the service but on the the dedicated interface like Injectable.Alternatively, with Spring at least, enabling Cglib proxy mode can help.

关于jakarta-ee - JAX-RS (Apache CXF) 通过 setter 进行上下文注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27855963/

相关文章:

android - 如何在Java类中导入kotlin数据类

java - jstat : -gccapacity output

java - 使用 CDI : Service stays null 时休息服务将无法工作

java - 在 java/JSP 中迭代 Map

android - 如何在 kotlin 中获取 ISO 8601 格式的当前日期和时间?

javafx - 如何防止表格隐藏TornadoFX

java - 如何在 jsp 文件中的查询语句中使用从 servlet 检索的数据?

java - 泽西客户端 API 问题

java - 返回新生成的 id restful service post

java - 如何解决 Jackson 无法处理 JPA bean 中的直接自引用的问题