本文由 简悦 SimpRead 转码, 原文地址 blog.csdn.net
问题
以 @Autowired 方式注入 PasswordEncoder 对登录密码进行校验,启动时报错如下
Description:
Field userService in com.lyx.springboot.controller.UserController required a bean of type 'org.springframework.security.crypto.password.PasswordEncoder' that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'org.springframework.security.crypto.password.PasswordEncoder' in your configuration.
在配置类里已经以 @Bean 形式声明了 PasswordEncoder,但是不生效。
@AutoConfiguration
@EnableConfigurationProperties(SecurityProperties.class)
public class SecurityConfiguration {
@Resource
private SecurityProperties securityProperties;
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(4);
}
}
解决方法
第一种方法:在启动类里以 @Bean 声明
@SpringBootApplication(scanBasePackages = "com.lyx.springboot.*")
public class SpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootApplication.class, args);
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(4);
}
}
第二种方法:在应用的代码处创建实例实现 PasswordEncoder 接口,如我用到的是 BCryptPassword
boolean result = new BCryptPasswordEncoder().matches(userDTO.getPassword(), userLogin.getPassword());