SpringBoot报Consider defining a bean of type ‘xxx’ in your configuration怎么解决

今天再跑SpringBoot项目时,在新加入SpringSecurity的时候,项目一直报错,跑不起来,报错原因如下:

报错的原因就是因为我引入的PasswordEncoder没有被注入到spring bean容器,导致无法启动,所以我们需要手动就PasswordEncoder注入到bean容器中去,但是springboot有自己独特的注入方式,所以在这里记录一下,防止上了年纪以后忘记了,首先贴上我的程序代码:

@Component
public class MyUserDetailsService implements UserDetailsService {

    
    @Autowired
    //这里用到了PasswordEncoder,但是spring并没有帮我们自动注入,所以报错
    private PasswordEncoder passwordEncoder;

    
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        String username = s;
        System.out.println("用户名为"+username);
        //根据username去数据库里查询获得密码
        String password = passwordEncoder.encode("123456");
        System.out.println("数据库密码为:"+password);
        return new User(username, passwordEncoder.encode("123456"),
                true,true,true,true,
                AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
;
    }
}

因为PasswordEncoder并没有被spring自动注入到我们的容器中,所以报了上诉的错误,通过查看源码,找到一个PasswordEncoder的实现类,然后手动注入进spring的容器中,问题得以解决,代码如下:

//说明这个一个配置类,类似spring中的xml文件
@Configuration
public class PasswordConfig {

    //手动将PasswordEncoder注入到ioc容器中
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }


}

再次运行项目后,程序恢复正常,希望可以帮到你们!

  • 8
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值