在springBoot中我们有时候需要让项目在启动时提前加载相应的数据或者执行某个方法,那么实现提前加载的方式有哪些呢?接下来我带领大家逐个解答
1.实现ServletContextAware接口并重写其setServletContext方法
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
注意:该方法会在填充完普通Bean的属性,但是还没有进行Bean的初始化之前执行
2.实现ServletContextListener接口
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /** 2 * 在初始化Web应用程序中的任何过滤器或servlet之前,将通知所有servletContextListener上下文初始化。 3 */ 4 @Override 5 public void contextInitialized(ServletContextEvent sce) { 6 //ServletContext servletContext = sce.getServletContext(); 7 System.out.println("执行contextInitialized方法"); 8 }
3.将要执行的方法所在的类交个spring容器扫描(@Component),并且在要执行的方法上添加@PostConstruct注解或者静态代码块执行(推荐)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 @Component 2 public class Test2 { 3 //静态代码块会在依赖注入后自动执行,并优先执行 4 static{ 5 System.out.println("---static--"); 6 } 7 /** 8 * @Postcontruct’在依赖注入完成后自动调用 9 */ 10 @PostConstruct 11 public static void haha(){ 12 System.out.println("@Postcontruct’在依赖注入完成后自动调用"); 13 } 14 }
4.实现ApplicationRunner接口 或 实现CommandLineRunner接口(推荐)
业务场景:
应用服务启动时,加载一些数据和执行一些应用的初始化动作。如:删除临时文件,清除缓存信息,读取配置文件信息,数据库连接等。
1、当接口有多个实现类时,提供了@order注解实现自定义执行顺序,也可以实现Ordered接口来自定义顺序。
注意:数字越小,优先级越高,也就是@Order(1)注解的类会在@Order(2)注解的类之前执行。
两者的区别在于:
ApplicationRunner中run方法的参数为ApplicationArguments,而CommandLineRunner接口中run方法的参数为String数组。想要更详细地获取命令行参数,那就使用ApplicationRunner接口
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /** 2 * 用于指示bean包含在SpringApplication中时应运行的接口。可以定义多个applicationrunner bean 3 * 在同一应用程序上下文中,可以使用有序接口或@order注释对其进行排序。 4 */ 5 @Override 6 public void run(ApplicationArguments args) throws Exception { 7 System.out.println("ApplicationRunner的run方法"); 8 }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /** 2 * 用于指示bean包含在SpringApplication中时应运行的接口。可以在同一应用程序上下文中定义多个commandlinerunner bean,并且可以使用有序接口或@order注释对其进行排序。 3 * 如果需要访问applicationArguments而不是原始字符串数组,请考虑使用applicationrunner。 4 * 5 */ 6 @Override 7 public void run(String... ) throws Exception { 8 System.out.println("CommandLineRunner的run方法"); 9 }
转自:https://javazhiyin.blog.csdn.net/article/details/113533177
https://blog.csdn.net/weixin_38362455/article/details/83023025