Spring Boot 为什么我的会话作用域Bean抛出“未找到线程绑定请求”

ddrv8njm  于 11个月前  发布在  Spring
关注(0)|答案(1)|浏览(86)

在我的Sping Boot 中,我希望通过会话作用域bean实现身份验证。

@Service
@Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class AuthService {
    private User user;
    public boolean isLoggedIn() { return user != null; }
    ...
}

字符串
我定义了一个过滤器,在每个请求上运行,这样我就可以检查用户是否登录:

@Configuration
public class AuthenticationFilter implements Filter {
    @Autowired
    private AuthService service;

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain ch) {
        if (!service.isLoggedIn()) {
           ...
        }
    }
    ...
}


当应用程序调用service.isLoggedIn()时,我得到了一个异常:
org.springframework.beans.factory.support.ScopeNotActiveException:Error creating bean with name 'scopedTarget. authService':Scope 'session' is not active for current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException:No thread-bound request found:你指的是实际Web请求之外的请求属性,还是在原始接收线程之外处理请求?如果你实际上是在一个web请求中操作,并且仍然收到这个消息,那么你的代码可能是在DispatcherServlet之外运行的:在这种情况下,使用RequestContextFilter或RequestContextFilter公开
我怀疑我的设计是错误的。有什么方法可以让它工作吗?

kr98yfug

kr98yfug1#

我只需要在某个地方为RequestContext声明一个bean

@Configuration
public class ContextListener {
    @Bean
    public RequestContextListener requestContextListener() {
        return new RequestContextListener();
    }
}

字符串
然后您可以从一个singletone-scope(默认)bean开始使用会话作用域和请求作用域的bean。

相关问题