有时候我们需要在工具类中使用到一些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中的方法