Springboot 启动时加载自定义方法的方式
1. 实现 CommandLineRunner 接口或 ApplicationRunner 接口:这两个接口提供了一个 run 方法,在应用程序启动后立即执行。您可以在这个方法中编写您希望在应用程序启动时执行的代码。
2. 使用 @PostConstruct 注解:您可以将 @PostConstruct 注解添加到自定义类的方法上,该方法将在该类的实例被创建后立即执行。这样,您可以在该方法中编写您希望在应用程序启动时执行的代码。
3. 使用 ApplicationListener 接口:您可以实现 ApplicationListener 接口,并监听 ApplicationStartedEvent 事件。当应用程序启动时,该事件将被触发,您可以在监听器中编写您的自定义逻辑。
4. 使用 @EventListener 注解:您可以将 @EventListener 注解添加到自定义类的方法上,并指定要监听的事件类型。当指定的事件发生时,该方法将被调用,您可以在其中编写您的自定义逻辑。例如,您可以监听 ApplicationStartedEvent 事件
CommandLineRunner接口
CommandLineRunner 接口是Spring Boot提供的一个回调接口,可以在应用程序启动后执行特定的方法。可以创建一个实现 CommandLineRunner 接口的类,并重写 run 方法,在其中编写需要在启动时执行的逻辑
@Component
public class NettyApplication implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("项目已启动");
}
}
ApplicationRunner接口
ApplicationRunner 接口与 CommandLineRunner 接口类似,也是Spring Boot提供的一个回调接口,用于在应用程序启动后执行特定的方法。与 CommandLineRunner 不同的是, ApplicationRunner 的 run 方法接收一个 ApplicationArguments 对象,可以用于获取应用程序启动参数
@Component
public class NettyApplication implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("项目已启动.....");
}
}
PostConstruct注解
@PostConstruct 注解是Java EE提供的一个标准注解,用于指定在构造函数执行完毕后立即执行的方法。在Spring Boot中,您可以在任何一个Bean中使用 @PostConstruct 注解来标记需要在启动时执行的方法
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
/**
* 设置系统指定时区为上海时区
**/
@PostConstruct
public void setTimezone() {
TimeZone.setDefault(TimeZone.getTimeZone("Asia/Shanghai"));
}
}
ApplicationListener接口
ApplicationListener 是 Spring Framework 提供的一个接口,用于监听应用程序中的事件并执行相应的逻辑。可以实现 ApplicationListener 接口,并重写 onApplicationEvent 方法来处理特定的事件
接下来罗列下spring主要的内置事件:
ContextRefreshedEvent(容器刷新事件):当 Spring 容器初始化或刷新时触发该事件。这个事件可以用于执行初始化逻辑或加载缓存数据等操作。在整个应用程序生命周期中,可能会多次触发此事件。
使用场景:
- 执行一次性的初始化逻辑,如加载配置文件、读取数据库数据等。
- 加载缓存数据,以提高后续请求的响应速度。
ContextStartedEvent(容器启动事件):当调用 ConfigurableApplicationContext 的 start() 方法时,触发该事件。该方法用于启动 Spring 容器,通常与 ContextStoppedEvent 配对使用。
使用场景:
- 在容器启动时执行特定的操作,如启动定时任务调度器、开启消息队列等。
ContextStoppedEvent(容器停止事件):当调用 ConfigurableApplicationContext 的 stop() 方法时,触发该事件。该方法用于停止 Spring 容器,通常与 ContextStartedEvent 配对使用。
使用场景:
- 在容器停止时执行特定的操作,如停止定时任务调度器、关闭消息队列连接等。
ContextClosedEvent(容器关闭事件):当 Spring 容器关闭时触发该事件。在应用程序关闭之前,会依次触发 ContextStoppedEvent 和 ContextClosedEvent。
使用场景:
- 执行清理操作,如释放资源、保存未完成的任务、关闭数据库连接等。
RequestHandledEvent(请求处理事件):在 Web 应用程序中,当每个 HTTP 请求被处理完成后触发该事件。它提供了一些关于请求处理的信息,如处理时间、请求路径等。
使用场景:
- 记录请求处理的统计信息,如处理时间、请求量等。
- 进行性能分析和优化,如监控慢请求、识别热门路径等。
@Slf4j
@Component
public class NettyApplication implements ApplicationRunner, ApplicationListener<ContextClosedEvent> {
/**
* 项目停止时触发
**/
@Override
public void onApplicationEvent(ContextClosedEvent event) {
log.info("项目停止后触发");
}
/**
* 项目启动后触发
**/
@Override
public void run(ApplicationArguments args) {
log.info("项目启动后触发");
}
}