我在跟着视频敲代码的时候,将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注入的问题,但不知道究竟为什么会导致这种情况的发生,希望老师能解答一下,
非常感谢(。◕◡◕。)ノ