Springboot CommandLineRunner和ApplicationRunner

阅读数:57 评论数:0

跳转到新版页面

分类

python/Java

正文

一、概述

CommandLineRunner和ApplicationRunner接口是在容器启动成功后的最后一步回调。

参见:spring生命周期 中的springboot启动过程。

使用CommandLineRunner或ApplicationRunner接口创建bean,spring boot会自动监测到它们。

这两个接口都有一个run()方法,在实现接口时需要覆盖该方法,并使用@Component注解注册到Spring容器中。

我们可以创建多个实现CommandLineRunner和ApplicationRunner接口的类。为了使他们按一定顺序执行,可以使用@Order注解或实现Ordered接口。

二、CommandLineRunner

CommandLineRunner接口的run()方法接收String数组作为参数,即是最原始的参数,没有做任何处理;

@Component
@Slf4j
public class RunScript implements CommandLineRunner{
	
	@PreDestroy
	public void destory(){
		log.info("在程序关闭后执行");
	}

	@Override
	public void run(String... args) throws Exception {
		log.info("在程序启动后执行:"+args);
		
	}
}

三、ApplicationRunner

ApplicationRunner接口的run()方法接收ApplicationArguments对象作为参数,是对原始参数做了进一步的封装。

@Component
@Slf4j
public class RunScript implements ApplicationRunner{
	
	@Override
	public void run(ApplicationArguments args) throws Exception {
		log.info("在程序启动后执行:"+args);
		
	}
	
	@PreDestroy
	public void destory(){
		log.info("在程序关闭后执行");
	}
}

 




相关推荐

一、概述 springboot中有两种方式使用kafka时,直接使用kafka-client连接kafka服务;另一种是使用spring-kafka框架来连接kafka。 1、版本兼容 使用时要注意版

当然可以自己写redis的工具类,或者使用第三方开源jar包或代码,这里使用spring boot的集成类。 一、pom依赖 <dependency> <gro

websocket协议基于tcp的网络协议,它实现浏览器与器全双工通信。 spring boot2 +websocket 1、添加依赖 <pre clas

背景: 之前用spring boot+mybatis+oracle,现在要改成spring boot_mybatis+postgresql。 为了想让一套代码即可

共同点 都是用来表示Spring某个类是否可以接收HTTP请求。 不同点 @Controller标识一个spring类是Spring MVC c

系统异常捕获 参见:spring boot 2 全局异常处理 @ControllerAdvice(annotations = {RestController.class}) public class

从SSH(Structs/Spring/Hibernate)到SSM(SpringMVC/Spring/MyBatis),到现在一个S(Spring)就够的年代,可见Spring越来越重要了。<

@ConditionalOnMissingBean只能在@Bean注解的方法上使用。 可以给该注解传入参数例如@ConditionOnMissingBean(name = "exa

2.4版本之前 在之前,我们在yaml配置文件中,使用spring.profiles来定义不同环境的标识,比如下面这样: <pre class="language-ma

在SpringBoot框架中,我们使用最多的是Tomcat,这是SpringBoot默认的容器技术,而且是内嵌式的Tomcat。   同时,SpringBoot也支持Undertow容器,Undert