为什么我的会话范围 Bean 抛出“未找到线程绑定请求”

问题描述 投票:0回答:1

在我的 Spring 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: 创建名称为“scopedTarget.authService”的 bean 时出错:范围 “会话”对于当前线程不活动;考虑定义一个 如果您打算从某个 bean 引用它,则该 bean 的范围代理 单例;嵌套异常是 java.lang.IllegalStateException: No 发现线程绑定请求:您指的是请求属性吗 在实际的网络请求之外,或者在外部处理请求 最初的接收线程?如果您实际操作的范围是 网络请求并仍然收到此消息,您的代码可能是 在 DispatcherServlet 外部运行:在本例中,使用 要公开的 RequestContextListener 或 RequestContextFilter

我怀疑我设计错误。有什么办法可以让它发挥作用吗?

java spring-boot session javabeans
1个回答
0
投票

我只需要在某处为 RequestContextListener 声明一个 bean

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

然后您可以开始使用单调范围(默认)bean 中的会话范围和请求范围 bean。

© www.soinside.com 2019 - 2024. All rights reserved.