天津武清做网站,网页设计与制作教学计划,株洲在线网站的目标客户,ps怎么制作网页页面项目场景#xff1a;
本文介绍Spring Boot项目启动时执行指定的方法两种常用方式和他们之间的区别。 实现方案#xff1a; 方式一#xff1a;使用注解PostConstruct Component
public class PostConstructTest {PostConstructpublic void postConstruct() {System.out.prin…项目场景
本文介绍Spring Boot项目启动时执行指定的方法两种常用方式和他们之间的区别。 实现方案 方式一使用注解PostConstruct Component
public class PostConstructTest {PostConstructpublic void postConstruct() {System.out.println(启动时自动执行 PostConstruct 注解方法);}
}
优点 简单方便加上一个注解就行了。
缺点如果PostConstruct方法内的逻辑处理时间较长就会增加SpringBoot应用初始化Bean的时间进而增加应用启动的时间。因为只有在Bean初始化完成后SpringBoot应用才会打开端口提供服务所以在此之前应用不可访问。
建议轻量的逻辑可放在Bean的PostConstruct方法中耗时长的逻辑如果放在PostConstruct方法中可使用Async异步方法。 使用异步代码示例
Service
public class TestService {Async(testAsync) //指定线程池public void test() {System.out.println(------------------------异步方法开始 Thread.currentThread().getName());try {Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(----------------异步方法执行完了 Thread.currentThread().getName());}
}Component
public class PostConstructTest {Autowiredprivate TestService testService;PostConstructpublic void postConstruct() {System.out.println(启动时自动执行 PostConstruct 注解方法);testService.test();}
}
Spring Boot中多个PostConstruct注解执行顺序控制_多个postconstruct执行顺序-CSDN博客 方式二实现CommandLineRunner接口 Component
public class CommandLineRunnerImpl implements CommandLineRunner {Overridepublic void run(String... args) throws Exception {System.out.println(启动时自动执行 CommandLineRunner 的 run 方法);}
}
优点 项目已经初始化完毕才会执行方法所以不用等这个方法执行完就可以正常提供服务了。
缺点暂未发现。