Spring:获取SessionRegistry而不修改任何XML文件?

时间:2014-01-06 19:21:13

标签: xml spring session javabeans

根据像this one这样的文章,可以完全使用Spring而无需修改任何xml文件。所以没有修改任何XML文件,我正在尝试使用SessionRegistry访问所有当前登录的用户,就像它已完成here一样。到目前为止我所尝试的是,首先,创建一个像这样的Bean:

@Configuration
public class SomeClass {   
[...]
    @Bean
    SessionRegistry sessionRegistry() {
        return new SessionRegistryImpl();
    }
[...]
}

然后在我的控制器中注入Bean:

@Controller
public class SomeController {

    @Resource(name = "sessionRegistry")
    private SessionRegistryImpl sessionRegistry;

    @RequestMapping(value = { "/"})
    public String list() {
        List<Object> principals = sessionRegistry.getAllPrincipals();
    }
[...]
}

但是每当我打印出principals时,我就会得到一个空列表。所以我的假设是,可能只是按照我的方式创建Bean是不够的。但为什么?你对如何继续有任何建议吗?

1 个答案:

答案 0 :(得分:0)

首先,您需要确保在Spring Security配置中使用会话存储库。我猜你当前正在使用一个不同的SessionRepository实例。例如:

protected void configure(
        HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
            .anyRequest().authenticated()
            .and()
        .formLogin()
            .and()
        .sessionManagement()
            .maximumSessions(1)

                // This line is important otherwise a default instance
                // will be used that is different than your Bean
                .sessionRegistry(sessionRegistry())
                .expiredUrl("/login?expired");
}

@Bean
SessionRegistry sessionRegistry() {
    return new SessionRegistryImpl();
}

接下来,您需要确保指定了HttpSessionEventPublisher。这可以使用以下方法完成:

public class SecurityInitializer extends
        AbstractSecurityWebApplicationInitializer {

    @Override
    protected boolean enableHttpSessionEventPublisher() {
        return true;
    }
}

另请注意,您需要将@Resource类型更改为SessionRegistry而不是SessionRegistryImpl。例如:

@Resource(name = "sessionRegistry")
private SessionRegistry sessionRegistry;
相关问题