【问题标题】:Missing dependency for field when trying to inject a custom context with Jersey尝试使用 Jersey 注入自定义上下文时缺少字段依赖项
【发布时间】:2012-01-18 06:53:03
【问题描述】:

我有一个自定义上下文:

public class MyContext {
    public String doSomething() {...}
}

我创建了一个上下文解析器:

@Provider
public class MyContextResolver implements ContextResolver<MyContext> {

     public MyContext getContext(Class<?> type) {
         return new MyContext();
     }
}

现在我尝试在资源中注入它:

@Path("/")
public class MyResource {

    @Context MyContext context;

}

我收到以下错误:

SEVERE: Missing dependency for field: com.something.MyContext com.something.MyResource.context

相同的代码适用于 Apache Wink 1.1.3,但适用于 Jersey 1.10。

任何想法都会受到赞赏。

【问题讨论】:

    标签: java rest jersey jax-rs jsr311


    【解决方案1】:

    JAX-RS 规范不强制要求 Apache 提供的行为 眨眼。 IOW,您尝试在 Apache Wink 上使用的功能 使您的代码不可移植。

    要生成 100% JAX-RS 可移植代码,您需要注入 javax.ws.rs.ext.Providers 实例然后使用:

    ContextResolver<MyContext> r = Providers.getContextResolver(MyContext.class, null);
    MyContext ctx = r.getContext(MyContext.class);
    

    检索您的 MyContext 实例。

    在Jersey,也可以直接注入ContextResolver, 这为您节省了上面的一行代码,但请注意,这 策略也不是 100% 可移植的。

    【讨论】:

      【解决方案2】:

      实现InjectableProvider。最有可能通过扩展 PerRequestTypeInjectableProvider 或 SingletonTypeInjectableProvider。

      @Provider
      public class MyContextResolver extends SingletonTypeInjectableProvider<Context, MyContext>{
          public MyContextResolver() {
              super(MyContext.class, new MyContext());
          }
      }
      

      会让你有:

      @Context MyContext context;
      

      【讨论】:

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