当尝试使用Jersey注入自定义上下文时,字段缺少依赖项。

8

我有一个自定义上下文:

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 上失败了。

如果有任何想法,将不胜感激。

2个回答

10

JAX-RS规范没有要求提供Apache Wink的行为。换句话说,您尝试在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%可移植的。


0

实现一个InjectableProvider。最好通过扩展PerRequestTypeInjectableProvider或SingletonTypeInjectableProvider来完成。

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

会让你拥有:

@Context MyContext context;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接