springsecurity injection into PasswordEncoder leads to circular reference

Configure the user name and password after introducing spring security start

@Configuration
public class SecurityConfig3 extends WebSecurityConfigurerAdapter {
    
    
    @Autowired
//    @Lazy
    private PasswordEncoder passwordEncoder;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    
    
        //设置登录的用户名和密码
        auth.inMemoryAuthentication().withUser("liuyuan")
                .password(passwordEncoder.encode("123"))
                .roles("admin");
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
    
    
        return new BCryptPasswordEncoder(10);
    }
}

启动项目报错:
┌──->──┐
| securityConfig3 (field private org.springframework.security.crypto.password.PasswordEncoder com.liu.springsecuritylearning.config.SecurityConfig3.passwordEncoder)
└──<-──┘
Action:

Relying upon circular references is discouraged and they are prohibited by default. Update your application to remove the dependency cycle between beans. As a last resort, it may be possible to break the cycle automatically by setting spring.main.allow-circular-references to true.

Reason analysis: It should be that I injected PasswordEncoder into the container and at the same time I obtained PasswordEncoder from the container. There may be a container that does not know whether it is injected into my custom or the security comes with it.

Solution: Delay assembly of my passwordEncoder, wait until the container is initialized, and then assemble it when I use it, and lazy loading can be realized. Just remove the comment above

Guess you like

Origin blog.csdn.net/qq_43566782/article/details/129507619