事件上的Spring会话bean初始化

事件上的Spring会话bean初始化,spring,authentication,spring-security,session-bean,Spring,Authentication,Spring Security,Session Bean,在我的项目中,我需要SessionBean来存储与当前会话关联的对象。在会话被创建并且用户被认证时,我想将对象设置到我的bean Bean定义: <bean scope="session" class="org.example.SessionBean"> <aop:scoped-proxy/> </bean> 我该怎么做?什么事件或侦听器将允许我使用当前用户初始化SessionBean。Spring Security在任何Servlet之前以及在Di

在我的项目中,我需要SessionBean来存储与当前会话关联的对象。在会话被创建并且用户被认证时,我想将对象设置到我的bean

Bean定义:

<bean scope="session" class="org.example.SessionBean">
    <aop:scoped-proxy/>
</bean>

我该怎么做?什么事件或侦听器将允许我使用当前用户初始化SessionBean。

Spring Security在任何
Servlet
之前以及在
DispatcherServlet
之前使用
过滤器进行操作。为了能够使用
request
session
作用域bean,需要
RequestContext
。这通常由
DispatcherServlet
编制。当想要在
DispatcherServlet
之外使用作用域bean时,需要进行一些额外的设置。如例外情况所述:

使用RequestContextListener或RequestContextFilter公开当前请求

要修复此问题,请将或添加到
web.xml
。使用后者时,请确保它在
springSecurityFilterChain
之前执行,否则它不会生效。侦听器总是在任何筛选器之前执行

public class SpringAuthenticationListener implements ApplicationListener<ApplicationEvent> {

private LogService logService;

private UserService userService;

@Autowired
private SessionBean sessionBean;

public SpringAuthenticationListener(LogService logService, UserService userService) {
    this.logService = logService;
    this.userService = userService;
}

@Override
public void onApplicationEvent(ApplicationEvent e) {
    LogEvent logEvent = new LogEvent();

    if (e instanceof AuthenticationSuccessEvent) {
        AuthenticationSuccessEvent event = (AuthenticationSuccessEvent) e;
        UserDetails userDetails = (UserDetails) event.getAuthentication().getPrincipal();

        User loggedUser = userService.getUser( userDetails.getUsername() );
        sessionBean.setLoggedUser(loggedUser);
    } 
}
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.org.example.SessionBean#0': Scope 'session' is not active for the 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: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.