溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

SpringBoot?@Autowired注入為空的原因有哪些

發(fā)布時間:2023-03-06 16:01:07 來源:億速云 閱讀:186 作者:iii 欄目:開發(fā)技術(shù)

今天小編給大家分享一下SpringBoot @Autowired注入為空的原因有哪些的相關(guān)知識點,內(nèi)容詳細,邏輯清晰,相信大部分人都還太了解這方面的知識,所以分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后有所收獲,下面我們一起來了解一下吧。

    @Autowired注入為空的情況解讀

    因最近在開發(fā)中遇到了使用@Autowired注解 自動裝配時,會報空指針,發(fā)現(xiàn)對象并沒有裝配進來,通過查詢,總結(jié)了幾種可能造成這種情況的原因。

    1.最簡單的一種情況,查看被裝配的類,也就是@Autowired注解下的類是否添加了注解交給SpringBoot托管,@service等注解,或者是直接加上@Component注解。

    2.看你的xxxxxApplication是否在根目錄,因為springboot默認掃描的就是啟動類下的目錄(這個我記著只限于Springboot2.0.5之前的版本,因為新版可以通過@ComponenScan注解去指定掃描范圍)。

    3.@Service、@Componet、@Configuration、@Repository等Spring注解未被掃描到,例如:springboot的主類掃描規(guī)則,就是說需要查看你的Springboot啟動類,xxxxxApplication,查看啟動類上注解是否加了@ComponenScan注解,是否指定了掃描范圍。

    使用springboot啟動類配置掃描的兩種注解配置方式:

    • 1、@Controller @EnableAutoConfiguration @ComponentScan 。

    • 2、@SpringBootApplication

    4.使用救急方法,這是如果沒找到原因,我們先使用其他方法讓程序先能正常運行和調(diào)試,后續(xù)再查找問題。

    @Autowired
     private SchedulerFactoryBean schedulerFactoryBean;
        
     private static QuartzManager quartzManager;
        
     /**
      * 通過@PostConstruct實現(xiàn)初始化bean之前進行的操作
      * @desc 初始化操作,得到QuartzManager實例
      * @Date 2019年1月7日
      */
     @PostConstruct 
     public void init() {  
          quartzManager = this;  
          quartzManager.schedulerFactoryBean = this.schedulerFactoryBean;        
    }

    使用@PostConstruct 初始化。

    5.這個原因很重要,也是經(jīng)常會被忽略的一個因素。調(diào)用者是new出來的。如果類A中存在成員屬性B, B是通過@Autowired自動注入,而類A的實例是通過new的方式產(chǎn)生的,那么自動注入會失效的,此時通過Spring的上下文獲取所有的Bean的方法來獲取B。此時,看看你在報空指針的那個類,看它是否是被new出來的,如果是,不妨使用SpringUtil.getBean()方法替換下, 然后再試下!

    @Autowired注入bean找不到異常

    異常描述

    ***************************
    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.service.ClientAuthService' that could 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.

    問題原因

    這個問題是環(huán)境問題,在Profiles 中之前是dev 環(huán)境

    SpringBoot?@Autowired注入為空的原因有哪些

    以上就是“SpringBoot @Autowired注入為空的原因有哪些”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家閱讀完這篇文章都有很大的收獲,小編每天都會為大家更新不同的知識,如果還想學習更多的知識,請關(guān)注億速云行業(yè)資訊頻道。

    向AI問一下細節(jié)

    免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

    AI