【问题标题】:How to inject prototype bean in Spring AuthenticationSuccessHandler implementation如何在 Spring AuthenticationSuccessHandler 实现中注入原型 bean
【发布时间】:2014-10-21 11:55:44
【问题描述】:

我正在使用 Spring security AuthenticationSuccessHandler 进行登录验证。

@Component
public class LoginAuthenticationHandler  implements AuthenticationSuccessHandler {
….

我在LoginAuthenticationHandler中注入UserData,如下

@Autowired
UserData userData;

UserData 应该是原型。

当我在 LoginAuthenticationHandler 中为不同的用户 [在用户登录时] 打印 userData 的哈希码时,哈希码是相同的。它告诉我 UserData bean 不能作为原型工作。

这是 spring-security.xml 中的 LoginAuthenticationHandler 定义

<beans:bean id="authenticationSuccessHandler" class="com.org.login.handler.LoginAuthenticationHandler" scope="prototype">
</beans:bean> 

这是 UserData bean 类

@Service
@Scope("prototype")
public class UserDataImpl implements UserData {

使 UserData 成为“真实”原型的选项是什么

【问题讨论】:

  • 实际上它是作为原型工作的。每次请求新实例时,您都会获得一个新实例。但是,唯一创建的新实例是在启动时。将原型注入单例会为该单例 bean 创建一个特定实例。如果您将 UserData 注入 2 个不同的 bean,您将获得 2 个实例。简而言之,如果您希望它的行为像原型一样,请不要自动装配,请进行查找,或者改用请求范围的 bean。它仍然提供相同的哈希码,但随后用于动态代理。

标签: java spring dependency-injection spring-security


【解决方案1】:

首先,您已经定义了两次 LoginAuthenticationHandler bean(注解和 XML),不要那样做。

当您想在单例 bean 中使用原型 bean 时,您必须使用代理。更改您的范围注释:

@Scope(value="prototype", proxyMode=ScopedProxyMode.INTERFACES)

【讨论】:

    【解决方案2】:

    显然,你们都在用 @Component 注释 LoginAuthenticationHandler,使其成为自动发现的 Spring bean,并在 XML 配置中声明它。由注解创建的 bean 将是一个单例,而从 XML 创建的将是一个原型。您还没有展示您实际如何使用该 bean,但系统的其余部分使用单例版本是理所当然的。当然,该版本在创建单例时分配了一次 UserData 的单个实例。

    要继续前进,首先用LoginAuthenticationHandler的声明来澄清情况。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-22
      • 1970-01-01
      • 2017-10-19
      相关资源
      最近更新 更多