Spring Boot的ApplicationRunner与CommandLineRunner接口的使用与区别

本文介绍SpringBoot中CommandLineRunner和ApplicationRunner接口的应用,用于在应用启动时执行特定任务。ApplicationRunner能更详细地处理命令行参数,两者可通过@Order注解控制执行顺序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、应用场景

在开发过程中会有这样的场景:需要在容器启动的时候执行一些内容,如读取配置文件信息,清除缓存信息等。在Spring框架下是通过ApplicationListener监听器来实现的。在Spring Boot中,我们也可以根据下面要提到的两个接口来帮助我们实现这样的需求。这两个接口就是CommandLineRunner和ApplicationRunner,它们的执行时机是容器启动完成的时候。

二、共同点与区别

共同点:

1)执行时机都是在容器启动完成的时候进行;

2)这两个接口中都有一个run()方法

不同点:

ApllicationRunner中run方法的参数为ApplicationArguments,而CommandLineRunner接口的run方法的参数为String数组。这两个接口间没有很大的区别,如果想要更详细地获取命令行参数,那就使用ApplicationRunner接口。

三、如何修改执行顺序

如果有多个实现类,我们需要按照一定的顺序执行的话,那么应该怎么办?

方案一:可以在实现类加上@Order注解指定执行的顺序

方案二:可以在实现类上实现Ordered来标识。

注意:数字越小,优先级越高,也就是@Order(1)注解的类会在@Order(2)注解的类之前执行。

四、案例分析

Spring Boot启动类:


@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        System.out.println("Spring BOOT 启动开始");
        SpringApplication.run(Application.class,args);
        System.out.println("Spring BOOT 启动结束");
    }
}

实现CommandLineRunner接口类:

@Component
public class CommandLineRunnerTest implements CommandLineRunner{
    @Override
    public void run(String[] args)throws Exception{
        System.out.println("CommandLineRunner=====执行开始");
        System.out.println("hehe");
        System.out.println("CommandLineRunner=====执行完毕");

    }
}

实现ApplicationRunner接口类:

@Component
public class ApplicationRunerTest implements ApplicationRunner{
    @Override
    public void run(ApplicationArguments args)throws Exception{
        System.out.println("ApplicationRunner=====执行开始");
        System.out.println(args.getNonOptionArgs());
        System.out.println(args.getOptionNames());
        System.out.println("ApplicationRunner=====执行完成");
    }
}

系统启动日志输出:

D:\Java\jdk1.8.0_152\bin\java -agentlib:jdwp=transport=dt_socket,address=127.0.0.1:2777,suspend=y,server=n -javaagent:C:\Users\chao\.IntelliJIdea2017.3\system\captureAgent\debugger-agent.jar=C:\Users\chao\AppData\Local\Temp\capture2129.props -Dfile.encoding=GBK -classpath "D:\Java\jdk1.8.0_152\jre\lib\charsets.jar;D:\Java\jdk1.8.0_152\jre\lib\deploy.jar;D:\Java\jdk1.8.0_152\jre\lib\ext\access-bridge-64.jar;D:\Java\jdk1.8.0_152\jre\lib\ext\cldrdata.jar;D:\Java\jdk1.8.0_152\jre\lib\ext\dnsns.jar;D:\Java\jdk1.8.0_152\jre\lib\ext\jaccess.jar;D:\Java\jdk1.8.0_152\jre\lib\ext\jfxrt.jar;D:\Java\jdk1.8.0_152\jre\lib\ext\localedata.jar;D:\Java\jdk1.8.0_152\jre\lib\ext\nashorn.jar;D:\Java\jdk1.8.0_152\jre\lib\ext\sunec.jar;D:\Java\jdk1.8.0_152\jre\lib\ext\sunjce_provider.jar;D:\Java\jdk1.8.0_152\jre\lib\ext\sunmscapi.jar;D:\Java\jdk1.8.0_152\jre\lib\ext\sunpkcs11.jar;D:\Java\jdk1.8.0_152\jre\lib\ext\zipfs.jar;D:\Java\jdk1.8.0_152\jre\lib\javaws.jar;D:\Java\jdk1.8.0_152\jre\lib\jce.jar;D:\Java\jdk1.8.0_152\jre\lib\jfr.jar;D:\Java\jdk1.8.0_152\jre\lib\jfxswt.jar;D:\Java\jdk1.8.0_152\jre\lib\jsse.jar;D:\Java\jdk1.8.0_152\jre\lib\management-agent.jar;D:\Java\jdk1.8.0_152\jre\lib\plugin.jar;D:\Java\jdk1.8.0_152\jre\lib\resources.jar;D:\Java\jdk1.8.0_152\jre\lib\rt.jar;G:\springboot-learning-example\springboot-helloworld\target\classes;G:\repository\org\springframework\boot\spring-boot-starter-web\1.5.1.RELEASE\spring-boot-starter-web-1.5.1.RELEASE.jar;G:\repository\org\springframework\boot\spring-boot-starter\1.5.1.RELEASE\spring-boot-starter-1.5.1.RELEASE.jar;G:\repository\org\springframework\boot\spring-boot\1.5.1.RELEASE\spring-boot-1.5.1.RELEASE.jar;G:\repository\org\springframework\boot\spring-boot-autoconfigure\1.5.1.RELEASE\spring-boot-autoconfigure-1.5.1.RELEASE.jar;G:\repository\org\springframework\boot\spring-boot-starter-logging\1.5.1.RELEASE\spring-boot-starter-logging-1.5.1.RELEASE.jar;G:\repository\ch\qos\logback\logback-classic\1.1.9\logback-classic-1.1.9.jar;G:\repository\ch\qos\logback\logback-core\1.1.9\logback-core-1.1.9.jar;G:\repository\org\slf4j\slf4j-api\1.7.22\slf4j-api-1.7.22.jar;G:\repository\org\slf4j\jcl-over-slf4j\1.7.22\jcl-over-slf4j-1.7.22.jar;G:\repository\org\slf4j\jul-to-slf4j\1.7.22\jul-to-slf4j-1.7.22.jar;G:\repository\org\slf4j\log4j-over-slf4j\1.7.22\log4j-over-slf4j-1.7.22.jar;G:\repository\org\springframework\spring-core\4.3.6.RELEASE\spring-core-4.3.6.RELEASE.jar;G:\repository\org\yaml\snakeyaml\1.17\snakeyaml-1.17.jar;G:\repository\org\springframework\boot\spring-boot-starter-tomcat\1.5.1.RELEASE\spring-boot-starter-tomcat-1.5.1.RELEASE.jar;G:\repository\org\apache\tomcat\embed\tomcat-embed-core\8.5.11\tomcat-embed-core-8.5.11.jar;G:\repository\org\apache\tomcat\embed\tomcat-embed-el\8.5.11\tomcat-embed-el-8.5.11.jar;G:\repository\org\apache\tomcat\embed\tomcat-embed-websocket\8.5.11\tomcat-embed-websocket-8.5.11.jar;G:\repository\org\hibernate\hibernate-validator\5.3.4.Final\hibernate-validator-5.3.4.Final.jar;G:\repository\javax\validation\validation-api\1.1.0.Final\validation-api-1.1.0.Final.jar;G:\repository\org\jboss\logging\jboss-logging\3.3.0.Final\jboss-logging-3.3.0.Final.jar;G:\repository\com\fasterxml\classmate\1.3.3\classmate-1.3.3.jar;G:\repository\com\fasterxml\jackson\core\jackson-databind\2.8.6\jackson-databind-2.8.6.jar;G:\repository\com\fasterxml\jackson\core\jackson-annotations\2.8.0\jackson-annotations-2.8.0.jar;G:\repository\com\fasterxml\jackson\core\jackson-core\2.8.6\jackson-core-2.8.6.jar;G:\repository\org\springframework\spring-web\4.3.6.RELEASE\spring-web-4.3.6.RELEASE.jar;G:\repository\org\springframework\spring-aop\4.3.6.RELEASE\spring-aop-4.3.6.RELEASE.jar;G:\repository\org\springframework\spring-beans\4.3.6.RELEASE\spring-beans-4.3.6.RELEASE.jar;G:\repository\org\springframework\spring-context\4.3.6.RELEASE\spring-context-4.3.6.RELEASE.jar;G:\repository\org\springframework\spring-webmvc\4.3.6.RELEASE\spring-webmvc-4.3.6.RELEASE.jar;G:\repository\org\springframework\spring-expression\4.3.6.RELEASE\spring-expression-4.3.6.RELEASE.jar;G:\repository\junit\junit\4.12\junit-4.12.jar;G:\repository\org\hamcrest\hamcrest-core\1.3\hamcrest-core-1.3.jar;C:\Program Files\JetBrains\IntelliJ IDEA 2017.3\lib\idea_rt.jar" org.spring.springboot.Application
Connected to the target VM, address: '127.0.0.1:2777', transport: 'socket'
Spring BOOT 启动开始

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.1.RELEASE)

2019-08-11 12:33:13.941  INFO 416 --- [           main] org.spring.springboot.Application        : Starting Application on LAPTOP-CRSICKSO with PID 416 (G:\springboot-learning-example\springboot-helloworld\target\classes started by chao in G:\springboot-learning-example\springboot-helloworld)
2019-08-11 12:33:13.947  INFO 416 --- [           main] org.spring.springboot.Application        : No active profile set, falling back to default profiles: default
2019-08-11 12:33:14.072  INFO 416 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@6892b3b6: startup date [Sun Aug 11 12:33:14 GMT+08:00 2019]; root of context hierarchy
2019-08-11 12:33:16.253  INFO 416 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration' of type [class org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-08-11 12:33:16.412  INFO 416 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'validator' of type [class org.springframework.validation.beanvalidation.LocalValidatorFactoryBean] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-08-11 12:33:17.472  INFO 416 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8080 (http)
2019-08-11 12:33:17.501  INFO 416 --- [           main] o.apache.catalina.core.StandardService   : Starting service Tomcat
2019-08-11 12:33:17.503  INFO 416 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.11
2019-08-11 12:33:17.718  INFO 416 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-08-11 12:33:17.718  INFO 416 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 3656 ms
2019-08-11 12:33:17.936  INFO 416 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Mapping servlet: 'dispatcherServlet' to [/]
2019-08-11 12:33:17.947  INFO 416 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
2019-08-11 12:33:17.948  INFO 416 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2019-08-11 12:33:17.948  INFO 416 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2019-08-11 12:33:17.948  INFO 416 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
2019-08-11 12:33:18.478  INFO 416 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@6892b3b6: startup date [Sun Aug 11 12:33:14 GMT+08:00 2019]; root of context hierarchy
2019-08-11 12:33:18.626  INFO 416 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/]}" onto public java.lang.String org.spring.springboot.web.HelloWorldController.sayHello()
2019-08-11 12:33:18.633  INFO 416 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2019-08-11 12:33:18.634  INFO 416 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2019-08-11 12:33:18.698  INFO 416 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2019-08-11 12:33:18.698  INFO 416 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2019-08-11 12:33:18.792  INFO 416 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2019-08-11 12:33:19.366  INFO 416 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2019-08-11 12:33:19.619  INFO 416 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
ApplicationRunner=====执行开始
[]
[]
ApplicationRunner=====执行完成
CommandLineRunner=====执行开始
hehe
CommandLineRunner=====执行完毕
2019-08-11 12:33:19.629  INFO 416 --- [           main] org.spring.springboot.Application        : Started Application in 6.381 seconds (JVM running for 7.409)
Spring BOOT 启动结束

由上述执行结果看:ApplicationRunner接口实现方法默认先于CommandLineRunner接口实现方法执行

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值