如果想在生成对象时候完成某些初始化操作,而偏偏这些初始化操作又依赖于依赖注入,那么就无法在构造函数中实现。为此,可以使用@PostConstruct注解一个方法来完成初始化,@PostConstruct注解的方法将会在依赖注入完成后被自动调用。
@PostConstruct是spring框架的注解,在方法上加该注解会在项目启动的时候执行该方法,也可以理解为在spring容器初始化的时候执行该方法。
@Service
public class ServiceImpl implements ServiceI {
public void taskstart() {
//TODO
}
@PostConstruct
public void init() {
FutureTask<String> task = new FutureTask<String>(new Callable<String>() {
@Override
public String call() throws Exception {
taskstart(); // 使用另一个线程来执行该方法
return "";
}
});
new Thread(task).start();
}
}
另外,Spring Boot应用程序在启动后,会遍历CommandLineRunner接口的实例并运行它们的run方法。也可以利用@Order注解(或者实现Order接口)来规定所有CommandLineRunner实例的运行顺序。多个CommandLineRunner可以被同时执行在同一个spring上下文中并且执行顺序是以order注解的参数顺序一致。
@Component
@Order(value = 1)
public class InitStartupRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
init();
}
}
如果你需要访问ApplicationArguments去替换掉字符串数组,可以考虑使用ApplicationRunner类。
@Component
@Order(value = 2)
public class InitRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
init();
}
}