ApplicationRunner——SpringBoot启动加载类

在实际开发项目中,我们总会遇到这样的情景,在项目启动后需进行初始化操作,最为常用的就是使用ApplicationRunner接口,然后使用该接口中的run()方法,在run()方法中进行你需要初始化的操作。

具体实现:

可以允许创建多个加载类,在类上加上@Oeder注解,并指定加载的顺序,数字越小,优先级越高 

启动程序

 

### 如何在Spring Boot应用启动时执行初始化操作 在Spring Boot应用程序中,可以通过多种方式来定义和执行初始化逻辑。以下是几种常见的方法: #### 方法一:使用`CommandLineRunner` `CommandLineRunner`是一个由Spring Boot提供的接口,在应用程序完成上下文加载后运行特定的代码片段。 ```java import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; @Component public class MyStartupRunner implements CommandLineRunner { @Override public void run(String... args) throws Exception { System.out.println("MyStartupRunner is running during application startup."); // 初始化逻辑可以放在这里[^1] } } ``` 此方法适用于需要访问Spring容器中的依赖项并执行某些业务逻辑的情况。 --- #### 方法二:使用`ApplicationListener<ContextRefreshedEvent>` 当Spring ApplicationContext完全刷新完毕时,会触发`ContextRefreshedEvent`事件。因此,你可以通过监听该事件来进行初始化工作。 ```java import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.stereotype.Component; @Component public class StartupInitializationListener implements ApplicationListener<ContextRefreshedEvent> { @Override public void onApplicationEvent(ContextRefreshedEvent event) { System.out.println("Executing initialization logic after context refresh."); // 可在此处编写自定义初始化逻辑[^3] } } ``` 这种方法适合于更复杂的场景,尤其是当你希望基于不同的生命周期阶段采取行动时。 --- #### 方法三:实现`SmartLifecycle` 如果需要更加精细地控制何时以及如何执行初始化逻辑,则可以选择让某个实现`SmartLifecycle`接口。 ```java import org.springframework.context.SmartLifecycle; import org.springframework.stereotype.Component; @Component public class CustomSmartLifecycle implements SmartLifecycle { private boolean isRunning = false; @Override public void start() { if (!isRunning) { System.out.println("CustomSmartLifecycle started."); this.isRunning = true; // 执行必要的初始化任务 } } @Override public void stop() { if (this.isRunning) { System.out.println("CustomSmartLifecycle stopped."); this.isRunning = false; } } @Override public boolean isRunning() { return this.isRunning; } } ``` 这种方式提供了更多的灵活性,允许开发者决定组件是否自动启动或停止。 --- #### 配置JMX支持(可选) 如果你的应用程序涉及监控需求,还可以启用Java Management Extensions (JMX),以便更好地跟踪和管理服务状态。这通常通过配置文件设置即可完成。 ```properties spring.jmx.enabled=true spring.jmx.default-domain=com.example.myapp ``` 上述属性确保了JMX功能被激活,并指定了默认域名称[^4]。 --- #### 总结 以上介绍了三种主要的方式用于处理Spring Boot应用启动期间的初始化过程——分别是利用`CommandLineRunner`、`ApplicationListener`以及`SmartLifecycle`机制。每种方案都有其适用范围,请根据实际项目需求选取最合适的选项。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值