为了实现在 Spring Boot 工程启动后,自动执行特定方法的功能,我们可以通过以下方式实现。
CommandLineRunner
实现 CommandLineRunner 接口,在 run 方法里面调用需要执行的方法即可。
特定:
- 方式执行时,项目已初始化完毕,可提供正常服务。
- 可以接受参数,不限制格式。项目启动时传入参数:
java -jar example.jar arg1 arg2 arg3 - 可直接注入 Spring IoC 容器的 bean。
代码示例:
| |
ApplicationRunner
实现 ApplicationRunner 接口与实现 CommandLineRunner 接口基本一致。
唯一不同是启动是参数的格式:CommandLineRunner 对于参数格式没有限制,ApplicationRunner 接口参数格式必须是 -key=value
代码示例:
| |
ApplicationListener
实现接口 ApplicationListener 方式和实现 ApplicationRunner、CommandLineRunner 接口都不影响服务,均可正常提供服务。
为了可以直接注入 bean,监听事件一般为 ApplicationStartedEvent 或 ApplicationReadyEvent,其他事件可能无法正常注入 bean。
代码示例:
| |
| |
其他方式
你也可以通过自定义 Spring Bean 初始化逻辑来实现程序启动时自动执行方法。
但一般此类方式均在项目启动过程中执行,且执行过程期间无法提供正常服务。
如使用 @PostConstruct 注解、实现 InitializingBean 接口、指定 init-method 方法等。
执行顺序
- 其他方式(通过自定义 Bean 初始化逻辑)始终最先执行。
- 如果监听
ApplicationStartedEvent事件,则一定会在CommandLineRunner和ApplicationRunner之前执行。 - 如果监听
ApplicationReadyEvent事件,则一定会在CommandLineRunner和ApplicationRunner之后执行。 CommandLineRunner和ApplicationRunner默认是ApplicationRunner先执行。如果指定了@Order则按照@Order大的先执行。


感谢您的耐心阅读!来选个表情,或者留个评论吧!