问题

以@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());

更多推荐