关于OAuth2AuthServerConfig中passwordEncoder和authenticationManager注入顺序的问题
来源:4-5 搭建OAuth2认证服务器
落尽余辉
2019-09-15
我在跟着视频敲代码的时候,将passwordEncoder写在authenticationManager之前:
@Configuration
@EnableAuthorizationServer
public class OAuth2AuthServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private AuthenticationManager authenticationManager;
其他的代码与老师写的一样,结果在启动时就出现了:
Error creating bean with name 'OAuth2AuthServerConfig': Unsatisfied dependency expressed through field 'passwordEncoder'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'OAuth2WebSecurityConfig': Unsatisfied dependency expressed through field 'userDetailsService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userDetailServiceImpl': Unsatisfied dependency expressed through field 'passwordEncoder'; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'passwordEncoder': Requested bean is currently in creation: Is there an unresolvable circular reference?
"Error creating bean with name ‘passwordEncoder’: Requested bean is there an unresolvable circular reference?"
看了一下感觉像是UserDetailServiceImpl和OAuth2WebSecurityConfig这两个类出现的循环引用?
有两种解决方法
一是将OAuth2AuthServerConfig中的注入顺序替换下,按照老师的写法
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private PasswordEncoder passwordEncoder;
二是移除passwordEncoder注入,改为本地变量直接使用
@Component
public class UserDetailServiceImpl implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
return User.withUsername(username)
.password(passwordEncoder.encode("123456"))
.authorities("ROLE_ADMIN").build();
}
}
搜了一圈找到类似的问题,却也没有正儿八经的解决思路,大概能知道是passwordEncoder注入的问题,但不知道究竟为什么会导致这种情况的发生,希望老师能解答一下,
非常感谢(。◕◡◕。)ノ
6回答
-
wesays
2019-11-19
我也是,我草 厉害了 谢谢谢
00 -
慕侠2481719
2019-10-05
感谢??,一样的问题卡了几天了
00 -
用银河口袋的露娜
2019-09-22
感谢感谢, 遇到同样的问题了
00 -
慕标8014184
2019-09-17
感谢感谢, 遇到同样的问题了
00 -
月光伴奏
2019-09-16
我遇到过这个问题 我是直接new passwordEncoder出来的 但在生产中UserDetailServiceImpl讲道理不会引用passwordEncoder
00 -
JoJo
2019-09-16
额...这我还真没注意,我就是随手一写,没在意顺序。等我回去试下:-)
012019-10-25
相似问题