一個神奇的標籤-@PostConstruct

1、問題描述

項目中封裝了個restTemplate的靜態調用類,統一調用外圍接口,但是發現外圍系統有些接口反應時間不穩定,還存在失敗的情況,爲了便於追蹤問題,將對外圍系統的入參和出參以及響應時間寫入到數據庫中,但是項目中都是通過靜態類調用的,寫入數據的方法是動態方法,無法使用,記錄下解決方案,希望能幫助需要的朋友。

2、解決方案

2.1 簡單介紹

簡單說就是用使用jdk提供的@PostConstruct這個標籤來實現,先介紹下@PostConstruct這個神奇的標籤。

Java中該註解的說明:@PostConstruct該註解被用來修飾一個非靜態的void()方法。被@PostConstruct修飾的方法會在服務器加載Servlet的時候運行,並且只會被服務器執行一次。PostConstruct在構造函數之後執行,init()方法之前執行。

重點說下執行順序:

通常我們會是在Spring框架中使用到@PostConstruct註解,該註解的方法在整個Bean初始化中的執行順序:

Constructor(構造方法) -> @Autowired(依賴注入) -> @PostConstruct(註釋的方法)

這個順序很重要,這樣我們就可以利用@Autowired注入的bean了。

2.2 代碼介紹

package com.laowang.spcrud.service;

import com.laowang.spcrud.db.entity.LPageInfo;
import com.laowang.spcrud.db.entity.TLaowang;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
/**
 * 軟件老王靜態調用service測試類
 */
@Component
public class StatisTest {

    public static StatisTest statisTest = new StatisTest(); //聲明對象

    //Spring注入
    @Autowired
    TestService testService;

    //初始化
    @PostConstruct
    public void init() {
        statisTest.testService = testService;
    }

    public static void staticPrint() {
        System.out.println("軟件老王是個大帥哥!");
    }

    public static void testMain() {
        StatisTest.staticPrint();
        
        List<TLaowang> list = statisTest.testService.selectAll(new LPageInfo(1, 2));
        System.out.println(list.toString());
    }
}

通過以上代碼可以看出來主要是以下三行代碼:

(1)new 一個靜態對象,這個時候對象裏面的testService是空值

public static StatisTest statisTest = new StatisTest(); //聲明對象

(2)spring通過標籤@Autowired注入servicebean

  @Autowired
  TestService testService;

(3)通過 @PostConstruct,將Spring注入的bean賦給new出來的StatisTest對象的testService

    //初始化
    @PostConstruct
    public void init() {
        statisTest.testService = testService;
    }

2.3 項目啓動

當項目啓動的時候,這個時候進入@PostConstruct的init方法的時候,發現statisTest對象的service是空的, 通過spring標籤@Autowired注入的TestService(bean),已經有值;

2.4 代碼驗證

2.4.1 controller中直接通過類.方法調用

    @RequestMapping(value ="/test", method = RequestMethod.POST)
    @ResponseBody
    public  void test() {
        StatisTest.testMain();
    }

2.4.2 swagger驗證

2.4.3 進入testmain方法

2.4.4 數據已經從數據庫中獲取到


更多信息請關注公衆號:「軟件老王」,關注不迷路,軟件老王和他的IT朋友們,分享一些他們的技術見解和生活故事。

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