简体   繁体   English

如何在Spring AuthenticationSuccessHandler实现中注入原型bean

[英]How to inject prototype bean in Spring AuthenticationSuccessHandler implementation

I am using Spring security AuthenticationSuccessHandler for my login validation. 我正在使用Spring security AuthenticationSuccessHandler进行登录验证。

@Component
public class LoginAuthenticationHandler  implements AuthenticationSuccessHandler {
….

I am injecting UserData in LoginAuthenticationHandler, as follows 我在LoginAuthenticationHandler中注入UserData,如下所示

@Autowired
UserData userData;

UserData should be prototype. UserData应该是原型。

When I print the hash code of userData inside LoginAuthenticationHandler for different users [at the user login time] the hash code is same. 当我在LoginAuthenticationHandler中为不同用户打印userData的哈希码时(在用户登录时),哈希码是相同的。 It tells me UserData bean is not working as prototype. 它告诉我UserData bean不能作为原型。

This is the LoginAuthenticationHandler definition from spring-security.xml 这是spring-security.xml中的LoginAuthenticationHandler定义

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

This is the UserData bean class 这是UserData bean类

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

What is the option to make the UserData a 'real' prototype 有什么方法可以使UserData成为“真实的”原型

First, you have defined your LoginAuthenticationHandler bean twice (annotation and XML), don't do that. 首先,您已经两次定义了LoginAuthenticationHandler bean(注释和XML),请不要这样做。

When you want to use a prototype bean inside a singleton bean, you must use a proxy. 如果要在单例bean中使用原型bean,则必须使用代理。 Alter your scope annotation: 更改范围注释:

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

Apparently you are both annotating your LoginAuthenticationHandler with @Component , making it an auto-discovered Spring bean, and declaring it in XML configuration. 显然,您都在用@Component注释LoginAuthenticationHandler ,使它成为自动发现的Spring bean,并在XML配置中声明了它。 The bean created by annotation will be a singleton, and the one created from XML will be a prototype. 通过注释创建的bean将是一个单例,而从XML创建的bean将是一个原型。 You haven't shown how you actually use that bean, but it stands to reason that the rest of the system is using the singleton version. 您尚未显示如何实际使用该bean,但可以推断,系统的其余部分使用的是singleton版本。 Of course, that version has its single instance of UserData assigned once, upon the creation of the singleton. 当然,创建单例后,该版本的UserData实例将分配一次。

To move forward first clear up the situation with the declaration of LoginAuthenticationHandler . 首先,请使用LoginAuthenticationHandler的声明消除这种情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM