有時候我們需要在工具類中使用到一些bean,比如在工具類中使用dao操作數據庫,就需要在工具類注入該依賴。要實現這個功能,需要用到@PostConstruct
注解,該注解用于注釋方法,被它注釋的方法會在依賴注入后執行。
假設我們需要在util中調用service里面的方法
@Service
public class TestService {
public void test() {
System.out.println("=========================================");
System.out.println("Test");
System.out.println("=========================================");
}
}
我們在工具類中定義一個指向自身的靜態成員變量,在依賴注入后把自身引用賦值給該靜態變量,那么我們就可以通過該變量去進行操作了
@Component
public class TestUtil {
@Autowired
private TestService testService;
private static TestUtil testUtil;
@PostConstruct
public void init() {
testUtil = this;
}
public static void test() {
testUtil.testService.test();
}
}
這樣就可以做到直接使用工具類去調用到service中的方法