gpt4 book ai didi

java - Guice:在 ServletModule 中注入(inject)拦截器

转载 作者:行者123 更新时间:2023-12-04 06:03:06 24 4
gpt4 key购买 nike

我正在尝试使用 Guice 创建的 Vaadin 应用程序实例注入(inject)一个拦截器。
我遵循了 Vaadin Wiki 中的 Vaadin-Guice 集成文档。和
Guice Wiki 中有关 Interceptor 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)

最佳答案

如果你把你的 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;
}
}

关于java - Guice:在 ServletModule 中注入(inject)拦截器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8712595/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com