Spring Boot注入PasswordEncoder失败

问题

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

相关推荐

  1. Spring Boot注入PasswordEncoder失败

    2024-02-18 14:02:06       51 阅读
  2. SpringBoot整理-依赖注入

    2024-02-18 14:02:06       49 阅读
  3. SpringBoot Mockito 依赖注入

    2024-02-18 14:02:06       35 阅读
  4. SpringBoot注解

    2024-02-18 14:02:06       69 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-02-18 14:02:06       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-02-18 14:02:06       101 阅读
  3. 在Django里面运行非项目文件

    2024-02-18 14:02:06       82 阅读
  4. Python语言-面向对象

    2024-02-18 14:02:06       91 阅读

热门阅读

  1. 【nginx实践连载-2】多应用安装部署

    2024-02-18 14:02:06       48 阅读
  2. Texas Instruments 在 GitHub 的官方主页

    2024-02-18 14:02:06       56 阅读
  3. 第1章 计算机网络体系结构-1.1计算机网络概述

    2024-02-18 14:02:06       44 阅读
  4. 【leetcode题解C++】455.分发饼干 and 376.摆动序列

    2024-02-18 14:02:06       58 阅读
  5. react中commit工作流程

    2024-02-18 14:02:06       52 阅读
  6. 【编程】Rust语言入门第4篇 字符串

    2024-02-18 14:02:06       51 阅读