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

编程知识 更新时间:2023-05-02 05:58:31

今天再跑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,
                AuthorityUtilsmaSeparatedStringToAuthorityList("admin"));
;
    }
}

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

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

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


}

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

更多推荐

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

本文发布于:2023-04-26 07:40:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/af0f0a5de6b28c11b70f75cc9e12e02d.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:bean   defining   SpringBoot   configuration   xxx

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!

  • 104767文章数
  • 26249阅读数
  • 0评论数