我正在使用BCryptPasswordEncoder来编码我的密码,但是当我使用它的编码功能来在UserService类的保存功能中对密码进行编码时,会出现此错误:
创建名称为'userController'的bean时出错:通过字段'userServiceInter'表示的不满意的依赖关系;嵌套的异常是org.springframework.beans.factory.UnsatisfiedDependencyException:创建名称为'userService'的bean时出错:通过字段'crypt'表示的不满足的依赖关系;嵌套的异常是org.springframework.beans.factory.NoSuchBeanDefinitionException:没有类型为“ org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder”的合格Bean:应该至少有1个有资格作为自动装配候选的Bean。依赖注释:{@ org.springframework.beans.factory.annotation.Autowired(required = true)}
当我删除它时可以使用,但是密码未编码。
UserService类:
@Service
public class UserService implements UserServiceInterface{
@Autowired
UserRepository repo;
@Autowired
BCryptPasswordEncoder crypt;
@Autowired
RoleRepository roleRepo;
public void save(User user) {
user.setPassword(crypt.encode(user.getPassword()));
Role role = roleRepo.findByRole("USER");
user.setRoles(new HashSet<Role>(Arrays.asList(role)));
repo.save(user);
}
@Override
public User findByUsername(String userName) {
User user = repo.findByUserName(userName);
return user;
}
}
UserServiceInterface:
@Service
public interface UserServiceInterface {
public void save(User user);
public User findByUsername(String userName);
}
SecurityConfiguration:
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends
WebSecurityConfigurerAdapter {
@Autowired
UserPrincipleDetailsService user;
@Autowired
private SimpleAuthenticationSuccessHandler successHandler;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws
Exception {
auth.authenticationProvider(daoAuthenticationProvider());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/assets/css/**").permitAll()
.antMatchers("/img/**").permitAll()
.antMatchers("/home").permitAll()
.antMatchers("/register/**").permitAll()
.antMatchers("/registerUser").permitAll()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/user/**").hasAnyRole("ADMIN","USER")
.anyRequest().authenticated()
.and()
.csrf().disable()
.formLogin()
.successHandler(successHandler)
.loginPage("/home").permitAll()
.loginProcessingUrl("/signin")
.failureUrl("/home?error=true")
.and()
.logout().logoutRequestMatcher(new
AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/home")
.and()
.exceptionHandling().accessDeniedPage("/home");
}
@Bean
DaoAuthenticationProvider daoAuthenticationProvider() {
DaoAuthenticationProvider dao = new
DaoAuthenticationProvider();
dao.setPasswordEncoder(passwordEncoder());
dao.setUserDetailsService(user);
return dao;
}
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
更改
@Autowired
BCryptPasswordEncoder crypt;
到
@Autowired
PasswordEncoder crypt
或更改passwordEncoder方法
@Bean
BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}