有時候我們需要在工具類中使用到一些bean,比如在工具類中使用dao操作數(shù)據(jù)庫,就需要在工具類注入該依賴。要實現(xiàn)這個功能,需要用到@PostConstruct注解,該注解用于注釋方法,被它注釋的方法會在依賴注入后執(zhí)行。
假設(shè)我們需要在util中調(diào)用service里面的方法
@Service
public class TestService {
public void test() {
System.out.println("=========================================");
System.out.println("Test");
System.out.println("=========================================");
}
}
我們在工具類中定義一個指向自身的靜態(tài)成員變量,在依賴注入后把自身引用賦值給該靜態(tài)變量,那么我們就可以通過該變量去進行操作了
@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();
}
}
這樣就可以做到直接使用工具類去調(diào)用到service中的方法