我有一个 POJO,我想将它注入到资源和过滤器中:
public final class MyObject { }
我为它实现了一个自定义提供程序:
@Provider
public final class MyProvider
extends AbstractHttpContextInjectable<MyObject>
implements InjectableProvider<Context, Type> {
@Context private HttpServletRequest request;
@Override
public Injectable<MyObject> getInjectable(
ComponentContext componentContext,
Context annotation,
Type type
) {
if (type.equals(MyObject.class)) {
return this;
}
return null;
}
@Override
public ComponentScope getScope() {
return ComponentScope.PerRequest;
}
@Override
public MyObject getValue(HttpContext httpContext) {
//in reality, use session info from injected request to create MyObject
return new MyObject();
}
}
该对象已成功注入我的资源:
@Path("/test")
@ResourceFilters(MyFilter.class)
public final class MyResource {
@Context private HttpServletRequest request;
@Context private MyObject myObject;
@GET
public String execute() {
System.out.println(request != null); //true
System.out.println(myObject != null); //true
return "data";
}
}
但泽西岛未能将其注入我的过滤器:
public final class MyFilter implements ResourceFilter {
@Context private HttpServletRequest request;
@Context private MyObject myObject;
@Override
public ContainerRequestFilter getRequestFilter() {
return new ContainerRequestFilter() {
@Override
public ContainerRequest filter(ContainerRequest containerRequest) {
System.out.println(request != null); //true
System.out.println(myObject != null); //false
return containerRequest;
}
};
}
@Override
public ContainerResponseFilter getResponseFilter() {
return null;
}
}
我猜测差异与以下事实有关,MyFilter
即注入是使用遵循线程本地实例的代理完成的 - 这是因为带有注释的字段@Context
是在外部类中声明的,它被实例化一次,但它们是用于基于每个请求注入对象。当我filter
在调试过程中单步执行时,我可以看到它MyFilter.request
指向一个包装了com.sun.jersey.server.impl.container.servlet.ThreadLocalInvoker
.
我的自定义提供程序(或其他实现)缺少什么需要对我的过滤器进行自定义注入?
请注意,我目前坚持使用 Jersey 1.1.4.1(对不起)。
编辑:使用 Jersey 1.17,我在启动时遇到异常:
严重:缺少字段的依赖项:private mypackage.MyObject mypackage.MyFilter.myObject