@Autowired注入為空的情況解讀
#因為最近在開發中遇到了使用@Autowired註解自動組裝時,會報空指針,發現物件並沒有組裝進來,透過查詢,總結了幾種可能造成這種情況的原因。
1.最簡單的一種情況,查看被組裝的類,也就是@Autowired註解下的類別是否添加了註解交給SpringBoot託管,@service等註解,或者是直接加上@Component註解。
2.看你的xxxxxApplication是否在根目錄,因為springboot預設掃描的就是啟動類別下的目錄(這個我記著只限於Springboot2.0.5之前的版本,因為新版可以透過@ComponenScan註解去指定掃描範圍)。
3.@Service、@Componet、@Configuration、@Repository等Spring註解未被掃描到,例如:springboot的主類掃描規則,就是說需要查看你的Springboot啟動類,xxxxxApplication,查看啟動類別上註解是否加了@ComponenScan註解,是否指定了掃描範圍。
使用springboot啟動類別配置掃描的兩種註解配置方式:
#1、@Controller @EnableAutoConfiguration @ComponentScan 。
2、@SpringBootApplication
#4.使用救急方法,這是如果沒找到原因,我們先使用其他方法讓程式先能正常運作和調試,後續再查找問題。
@Autowired private SchedulerFactoryBean schedulerFactoryBean; private static QuartzManager quartzManager; /** * 通过@PostConstruct实现初始化bean之前进行的操作 * @desc 初始化操作,得到QuartzManager实例 * @Date 2019年1月7日 */ @PostConstruct public void init() { quartzManager = this; quartzManager.schedulerFactoryBean = this.schedulerFactoryBean; }
使用@PostConstruct 初始化。
5.這個原因很重要,也是常常會被忽略的因素。呼叫者是new出來的。如果類別A中存在成員屬性B, B是透過@Autowired自動注入,而類別A的實例是透過new的方式產生的,那麼自動注入會失效的,此時透過Spring的上下文來取得所有的Bean的方法來獲取B。此時,看看你在報空指標的那個類,看它是否是被new出來的,如果是,不妨使用SpringUtil.getBean()方法替換下, 然後再試下!
@Autowired注入bean找不到例外
異常描述
問題原因這個問題是環境問題,在Profiles 之前是dev 環境#******************* ********
APPLICATION FAILED TO START
***************************Description:
Field clientAuthService in com.yinhai.mzgh.eurekaclient.feign.interceptor.Oauth3RequestInterceptor
required a bean of type 'com.yinhai.mzgh.eurekaclient.feign that.ClientA. 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 'com.yinhai.mzgh.eurekaclient.feign.service.ClientAuthService' in your configuration.
以上是SpringBoot @Autowired注入為空的原因有哪些的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

SublimeText3 Linux新版
SublimeText3 Linux最新版

SublimeText3漢化版
中文版,非常好用

Atom編輯器mac版下載
最受歡迎的的開源編輯器

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)