spring-data-jpa 在服务类中创建和注入BCryptPasswordEncoder时出错

mv1qrgav  于 2022-11-10  发布在  Spring
关注(0)|答案(2)|浏览(177)

我想散列密码并将其存储在数据库中。当我尝试将PasswordEncoder bean注入到我的服务类中时,我得到了下面提到的错误。
这是我第一个使用Spring-security模块的项目,非常感谢您的建议。

Spring Boot version:2.2.6.RELEASE

**安全配置.java:安全配置类 *

@EnableWebSecurity
    @Configuration
    @ComponentScan(basePackages = { "com.sd.authandauthorizationbackendapp.security" })
    public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    UserDetailsService userDetailsService;

    @Override
    @Bean
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
        auth.parentAuthenticationManager(authenticationManagerBean())
                .userDetailsService(userDetailsService).
                .and().authenticationProvider(authProvider());
    }

    @Bean
    public DaoAuthenticationProvider authProvider() {
        DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
        authProvider.setUserDetailsService(userDetailsService);
        authProvider.setPasswordEncoder(passwordEncoder());
        return authProvider;
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.httpBasic().and().csrf().disable().authorizeRequests()
                .antMatchers("/admin").hasRole("ADMIN")
                .antMatchers("/test").hasRole("USER")
                .antMatchers("/register").permitAll()
                .antMatchers("/").permitAll()
                .and().formLogin();
    }
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder(10, new SecureRandom());
    }
    }

用户服务实现java:一个服务类来保存用户

@Service
    public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    PasswordEncoder bCryptPasswordEncoder;

    @Override
    public void save(User user) {
        user.setPassword(bCryptPasswordEncoder.
                                  encode(user.getPassword()));
        user.setRoles(user.getRoles());
        userRepository.save(user);
    }
    }

错误

Unsatisfied dependency expressed through field 'bCryptPasswordEncoder';   Error creating 
bean with name 'passwordEncoder': Requested bean is currently in creation: Is there an 
unresolvable circular reference?

请让我知道,如果需要进一步的代码和细节。

gv8xihay

gv8xihay1#

除非你在服务类中使用@Qualified("passwordEncoder"),否则spring会将bCryptPasswordEncoder作为bean来查找,现在你正在查找一个名为bCryptPasswordEncoder的bean。
更改为

@Autowired
  PasswordEncoder passwordEncoder;

@Qualified("passwordEncoder")
 @Autowired
 PasswordEncoder bCryptPasswordEncoder;
hyrbngr7

hyrbngr72#

通过从PasswordEncoder中删除@Autowired,问题将得到解决。因为您正在同一个类中创建PasswordEncoder,您正在注入它。

相关问题