Missing dependency for field when trying to inject a custom context with Jersey

痞子三分冷 提交于 2019-12-05 21:36:57

问题


I have a custom context:

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

I have created a context resolver:

@Provider
public class MyContextResolver implements ContextResolver<MyContext> {

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

Now in the resource I try to inject it:

@Path("/")
public class MyResource {

    @Context MyContext context;

}

And I get the following error:

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

The same code works fine with Apache Wink 1.1.3, but fails with Jersey 1.10.

Any ideas will be appreciated.


回答1:


JAX-RS specification does not mandate the behavior provided by Apache Wink. IOW, the feature you are trying to use that works on Apache Wink makes your code non-portable.

To produce 100% JAX-RS portable code, you need to inject javax.ws.rs.ext.Providers instance and then use:

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

to retrieve your MyContext instance.

In Jersey, you can also directly inject ContextResolver, which saves you one line of code from the above, but note that this strategy is also not 100% portable.




回答2:


Implement a InjectableProvider. Most likely by extending PerRequestTypeInjectableProvider or SingletonTypeInjectableProvider.

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

Would let you have:

@Context MyContext context;


来源:https://stackoverflow.com/questions/8471603/missing-dependency-for-field-when-trying-to-inject-a-custom-context-with-jersey

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!