首頁  >  文章  >  Java  >  SpringBoot @Autowired注入為空的原因有哪些

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

PHPz
PHPz轉載
2023-05-14 18:40:153297瀏覽

    @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找不到例外

    異常描述

    #******************* ********
    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.

    問題原因

    這個問題是環境問題,在Profiles 之前是dev 環境

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

    以上是SpringBoot @Autowired注入為空的原因有哪些的詳細內容。更多資訊請關注PHP中文網其他相關文章!

    陳述:
    本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除