我有一个类,在其中创建一个 @Bean
,它是:
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
然后在其他类中我想使用它,但我不能,因为据说 Bean
尚未初始化。
类(class):
@Configuration
@ComponentScan(basePackages = "com.inventory")
@Order(SecurityProperties.ACCESS_OVERRIDE_ORDER)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
@Qualifier("databaseUsersDetailsService")
private UserDetailsService userDetailsService;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
在这里我想使用它:
@Service
public class SessionService {
private final UserDetailsService userDetailsService;
private final BCryptPasswordEncoder encoder;
private final AuthenticationManager authenticationManager;
@Autowired
public SessionService(UserDetailsService userDetailsService, BCryptPasswordEncoder encoder, AuthenticationManager authenticationManager) {
this.userDetailsService = userDetailsService;
this.encoder = encoder;
this.authenticationManager = authenticationManager;
}
在构造函数中,据说我无法使用它,因为没有找到 BCryptPasswordEncoder 的 beans
。
有人知道这里出了什么问题吗?我正在使用 Spring Boot。
最佳答案
您的 Spring 上下文中没有 BCryptPasswordEncoder
实例。实际上,您已经注册了一个 PasswordEncoder
类型的 bean,并且您应该准确地注入(inject)该类型的一个对象。
选择什么PasswordEncoder
实现并不重要,重要的是您在 Bean 注册期间声明的类型 .
关于java - 无法使用创建的bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48177261/