我有一个ContainerRequestFilter
来处理请求授权,我想将AuthService
接口的实现注入到它的构造函数中(我使用Guice for DI)。我一直无法弄清楚如何使依赖注入工作。
我的过滤器类看起来像这样:
public class UserRoleFilter implements ContainerRequestFilter {
protected AuthService authService;
@Context
private ResourceInfo resourceInfo;
@Inject
public UserRoleFilter(AuthService authService) {
this.authService = authService;
}
@Override
public void filter(ContainerRequestContext requestContext) {
this.authService.doSomething(...);
}
当我运行该程序时,我从NullPointerException
获得org.jboss.resteasy.core.ConstructorInjectorImpl.<init>
。
我的应用程序启动是:
public static void main(String[] args) throws Exception {
Injector injector = Guice.createInjector(new RestApplicationModule(args));
initServer(injector).join();
}
public static Server initServer(Injector injector) throws Exception {
Server server = new Server(SERVER_PORT);
ServletContextHandler servletHandler = new ServletContextHandler();
servletHandler.setInitParameter("resteasy.role.based.security", "true");
servletHandler.setInitParameter("resteasy.providers", UserRoleFilter.class.getName());
servletHandler.addEventListener(injector.getInstance(GuiceResteasyBootstrapServletContextListener.class));
servletHandler.addServlet(HttpServletDispatcher.class, "/*");
// Create the SessionHandler (wrapper) to handle the sessions
SessionManager manager = new HashSessionManager();
SessionHandler sessions = new SessionHandler(manager);
servletHandler.setSessionHandler(sessions);
server.setHandler(servletHandler);
server.start();
return server;
}
private static class RestApplicationModule extends RequestScopeModule {
public RestApplicationModule(String[] args) {
}
@Override
protected void configure() {
super.configure();
bind(AuthService.class).to(AuthServiceImpl.class);
bind(UserRoleFilter.class);
// Bind JAX-RS Controller classes
}
}
通过RestEasy初始代码的内容,看起来我 将@Context
属性添加到我的RestEasy构造函数中的authService
参数中接受它。传入代理对象并允许服务器启动,但是一旦过滤器尝试访问authService,我得到:
RESTEASY003880: Unable to find contextual data of type: com.genghiszahn.authFilterTest.AuthService