admin管理员组

文章数量:1794759

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

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

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

//说明这个一个配置类,类似spring中的xml文件 @configuration public class PasswordConfig { //手动将PasswordEncoder注入到ioc容器中 @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } }

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

本文标签: beandefiningSpringBootconfigurationxxx