IDEA Spring-boot 使用@Component註解的工具類,用@Autowired注入 @Service或者@Repository 會空指針(使用@PostContruct )

使用idea編譯器時,對於spring-boot的項目,大都使用註解,那麼:

一、現象:@Component標註的Util類,用@Autowired自動導入 @Service和@Repository會報空指針

二、原因:網上查閱的文章說,無法持久化引用

三、解決方法:

         1、增加一個靜態變量:  private static ClassNameUtil.java zKK;

         2、使用註解@PostContruct ,讓該util在啓動spring時,執行初始化方法(這樣util才存在,纔可以注入其他)

         3、調用方式:工具類名.引用類名.方法名(zKK.devicesRe.methd())

         4、例子:

@Component
public class ZKAndKafkaManageUtil implements IServiceControlCommonOperation{

    @Autowired
	DevicesRepository devicesRe;

    private static ZKAndKafkaManageUtil zKK;  //1、加個靜態變量

	@PostConstruct   //2、加個註解並初始化
	public void init (){
		zKK=this;
	}

        //3、引用,特別注意:引用方式爲: 工具類名.引用類名.方法名(zKK.devicesRe.methd())
        public void test2(){
    	    zKK.devicesRe.findDeviceByIpv4Addr("222.143.1.193"); 
	}

註解拓展:

1、@PostContruct是spring框架的註解,在方法上加該註解會在項目啓動的時候執行該方法,也可以理解爲在spring容器初始化的時候執行該方法

2、spring中Constructor、@Autowired、@PostConstruct的順序

其實從依賴注入的字面意思就可以知道,要將對象p注入到對象a,那麼首先就必須得生成對象p與對象a,才能執行注入。所以,如果一個類A中有個成員變量p被@Autowired註解,那麼@Autowired注入是發生在A的構造方法執行完之後的。

如果想在生成對象時候完成某些初始化操作,而偏偏這些初始化操作又依賴於依賴注入,那麼就無法在構造函數中實現。爲此,可以使用@PostConstruct註解一個方法來完成初始化,@PostConstruct註解的方法將會在依賴注入完成後被自動調用。

Constructor(構造) >> @Autowired(注入) >> @PostConstruct(調用)

public Class AAA {
    @Autowired
    private BBB b;
     
    public AAA() {
        System.out.println("此時b還未被注入: b = " + b);
    }
  
    @PostConstruct
    private void init() {
        System.out.println("@PostConstruct將在依賴注入完成後被自動調用: b = " + b);
    }
}

參考網址:

https://blog.csdn.net/weixin_42911069/article/details/88849789

https://www.cnblogs.com/kelelipeng/p/11309591.html

https://www.cnblogs.com/zxf330301/p/9265718.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章