1、Spring 基于监听 ContextRefreshedEvent 事件,在应用启动后完成初始化操作。Spring Boot 中也能使用这种方式。 2、Spring Boot 提供了 ApplicationRunner 和 CommandLineRunner 用于完成启动后的初始化工作,我们只要实现继承这个接口并实现其中的 run 方法就可以了。 3、ApplicationRunner 和 CommandLineRunner 都可以获得...
一、入门级:启动main方法中添加初始化逻辑 在Spring Boot的main入口启动方法中,执行SpringApplication.run(LimitApplication.class, args)是可以返回ApplicationContext对象的,我们可以从ApplicationContext中获取指定的bean对象,执行初始化逻辑。 @SpringBootApplication(scanBasePackages = {"com.laowan.limit"}) public class...
SpringApplicationRunListener:Spring Boot 内置的监听器,主要用于 SpringBoot 启动的整个过程。比如:初始化、环境准备、上下文准备和完全启动等多个阶段。 starting():在 run 方法首次启动时立即调用。可用于非常早期的初始化。 environmentPrepared():在准备好环境后但在创建环境之前 ApplicationContext 调用。 contextPrepa...
System.out.println("初始化:InitApplicationRunner"); } } ApplicationRunner接口的run()参数为ApplicationArguments对象,因此可以获取更多项目相关的内容。 ApplicationRunner接口与CommandLineRunner接口的调用时机也是相同的,都是Spring beans初始化之后。因此ApplicationRunner接口也使用@Order(n)来设置执行顺序。
2、SpringBoot的CommandLineRunner接口 当容器初始化完成之后会调用CommandLineRunner中的run()方法,同样能够达到容器启动之后完成一些事情。这种方式和ApplicationListener相比更加灵活,如下: 不同的CommandLineRunner实现可以通过@Order()指定执行顺序 可以接收从控制台输入的参数。
SpringBoot启动时,执行初始化方法的几种方式: 方法1:CommandLineRunner接口 importorg.springframework.boot.CommandLineRunner;@SpringBootApplicationpublicclassDemoAppimplementsCommandLineRunner{@AutowiredWebAppConfig appConfig;/** * main method */publicstaticvoidmain(String[] args){ ...
在Spring Boot 项目中,初始化操作是不可或缺的一部分。它们确保应用在启动时进行必要的配置、数据加载、资源初始化等工作。本文将深入探讨 Spring Boot 中常见的几种初始化操作方式,并对它们的执行顺序进行比较,帮助你选择最适合你项目的方案。 1. @PostConstruct ...
方案想好了就要想实现方式了,想个最直接的方案,在Spring容器初始化时就把这些数据从数据库拿到内存中,后面就直接调用。 SpringBoot中有两个接口能实现该功能:CommandLineRunner和ApplicationRunner。 2.1 CommandLineRunner 首先了解一下CommandLineRunner的基本用法,CommandLineRunner可以在系统启动后执行里面的run方法 ...
一种常见的要求是在应用程序启动后执行特定任务。这可能包括初始化数据、设置连接或执行健全性检查。在本文中,我们将深入研究可用于在 Spring Boot 启动后执行任务的各种选项,确保您的应用程序不仅可以正常运行,而且从一开始就可以实现最佳性能。 1、使用 CommandLineRunner 界面...