Guice:在ServletModule中注入拦截器

时间:2012-01-03 12:53:29

标签: java guice vaadin

我正在尝试使用Guice创建的Vaadin Application实例注入一个Interceptor。 我在Vaadin WikiGuice Wiki中遵循了Vaadin-Guice集成的文档 关于{{3}}中的拦截器DI的文件:

public class RecruitmentServletConfig extends GuiceServletContextListener {

    @Override
    protected Injector getInjector() {

        ServletModule servletModule = new ServletModule() {

            @Override
            protected void configureServlets() {
                ...
                bind(Application.class).to(RecruitmentApplication.class).in(ServletScopes.SESSION);
                SecurityGuard securityGuard = new SecurityGuard();
                requestInjection(securityGuard);
                bindInterceptor(Matchers.subclassesOf(CustomComponent.class), Matchers.annotatedWith(AllowedRoles.class), securityGuard);
            }
        };
        return Guice.createInjector(servletModule);
    }
}

SecurityGuard拦截器:

public class SecurityGuard implements MethodInterceptor {
    @Inject private Application application;

    public Object invoke(MethodInvocation invocation) throws Throwable {
        AllowedRoles allowedRoles = invocation.getMethod().getAnnotation(AllowedRoles.class);
        if (((User) application.getUser()).hasRole(allowedRoles.value())) {
            return invocation.proceed(); 
        } else {
            return null;
        }
}

但是,我在服务器启动时收到OutOfScopeException:

SEVERE: Exception sending context initialized event to listener instance of class de.embl.eicat.recruit.ioc.RecruitmentServletConfig
com.google.inject.CreationException: Guice creation errors:
1) Error in custom provider, com.google.inject.OutOfScopeException: Cannot access scoped object. Either we are not currently inside an HTTP Servlet request, or you may have forgotten to apply com.google.inject.servlet.GuiceFilter as a servlet filter for this request.
at recruit.ioc.RecruitmentServletConfig$1.configureServlets(RecruitmentServletConfig.java:86)

1 个答案:

答案 0 :(得分:3)

如果将Application包裹在Provider中,是否有效?

public class SecurityGuard implements MethodInterceptor {
    @Inject private Provider<Application> application;

    public Object invoke(MethodInvocation invocation) throws Throwable {
       AllowedRoles allowedRoles = invocation.getMethod().getAnnotation(AllowedRoles.class);
        if (((User) application.get().getUser()).hasRole(allowedRoles.value())) {
            return invocation.proceed(); 
        } else {
            return null;
        }
}