SpringBoot報Consider defining a bean of type ‘xxx’ in your configuration怎麼解決
阿新 • • 發佈:2018-12-12
今天再跑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(); } }
再次執行專案後,程式恢復正常,希望可以幫到你們!