在spring boot应用中,我们可以在程序启动之前执行任何任务。为了达到这个目的,我们需要使用CommandLineRunnerApplicationRunner接口创建bean,spring boot会自动监测到它们。这两个接口都有一个run()方法,在实现接口时需要覆盖该方法,并使用@Component注解使其成为bean。CommandLineRunnerApplicationRunner的作用是相同的。不同之处在于CommandLineRunner接口的run()方法接收String数组作为参数,而ApplicationRunner接口的run()方法接收ApplicationArguments对象作为参数。当程序启动时,我们传给main()方法的参数可以被实现CommandLineRunnerApplicationRunner接口的类的run()方法访问。我们可以创建多个实现CommandLineRunnerApplicationRunner接口的类。为了使他们按一定顺序执行,可以使用@Order注解或实现Ordered接口。

CommandLineRunnerApplicationRunner接口的run()方法在SpringApplication完成启动时执行。启动完成之后,应用开始运行。CommandLineRunnerApplicationRunner的作用是在程序开始运行前执行任务或记录信息。

下面展示了如何在程序中使用CommandLineRunnerApplicationRunner

Maven配置

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion>
<groupId>com.concretepage</groupId>
<artifactId>spring-boot-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>spring-demo</name>
<description>Spring Boot Demo Project</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.2.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

CommandLineRunner

CommandLineRunner是个接口,有一个run()方法。为了使用CommandLineRunner我们需要创建一个类实现该接口并覆盖run()方法。使用@Component注解实现类。当SpringApplication.run()启动spring boot程序时,启动完成之前,CommandLineRunner.run()会被执行。CommandLineRunnerrun()方法接收启动服务时传过来的参数。

run(String... args)

参数为String数组。

CommandLineRunnerBean.java

package com.concretepage.bean;

import java.util.Arrays;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component; @Component
public class CommandLineRunnerBean implements CommandLineRunner {
private static final Logger logger = LoggerFactory.getLogger(CommandLineRunnerBean.class);
public void run(String... args) {
String strArgs = Arrays.stream(args).collect(Collectors.joining("|"));
logger.info("Application started with arguments:" + strArgs);
}
}

MyApplication.java

package com.concretepage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import com.concretepage.service.HelloService; @SpringBootApplication
public class MyApplication {
private static final Logger logger = LoggerFactory.getLogger(MyApplication.class);
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(MyApplication.class, args);
HelloService service = context.getBean(HelloService.class);
logger.info(service.getMessage());
}
}

我们也可以创建一个service。一旦Spring boot启动完成service就会执行。这意味着SpringApplication.run()执行完成后service的方法就会执行。
HelloService.java

package com.concretepage.service;

import org.springframework.stereotype.Service;

@Service
public class HelloService {
public String getMessage(){
return "Hello World!";
}
}

现在使用带有参数的可执行jar运行程序。spring-boot-demo-0.0.1-SNAPSHOT.jar为生成的jar文件。执行命令如下:

java -jar spring-boot-demo-0.0.1-SNAPSHOT.jar data1 data2 data3

输出结果为:

2017-03-19 13:38:38.909  INFO 1036 --- [           main] c.c.bean.CommandLineRunnerBean           : Application started with arguments:data1|data2|data3
2017-03-19 13:38:38.914 INFO 1036 --- [ main] com.concretepage.MyApplication : Started MyApplication in 1.398 seconds (JVM running for 1.82)
2017-03-19 13:38:38.915 INFO 1036 --- [ main] com.concretepage.MyApplication : Hello World!

ApplicationRunner

ApplicationRunnerCommandLineRunner的作用相同。在SpringApplication.run()完成spring boot启动之前,ApplicationRunnerrun()方法会被执行。

run(ApplicationArguments args)

可以看到,CommandLineRunner.run()接收String数组作为参数,而ApplicationRunner.run()接收ApplicationArguments作为参数。这些参数是启动spring boot程序时传给main()方法的。

ApplicationRunnerBean.java

package com.concretepage.bean;

import java.util.Arrays;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component; @Component
public class ApplicationRunnerBean implements ApplicationRunner {
private static final Logger logger = LoggerFactory.getLogger(ApplicationRunnerBean.class);
@Override
public void run(ApplicationArguments arg0) throws Exception {
String strArgs = Arrays.stream(arg0.getSourceArgs()).collect(Collectors.joining("|"));
logger.info("Application started with arguments:" + strArgs);
}
}

创建可执行jar包并使用如下参数运行:

java -jar spring-boot-demo-0.0.1-SNAPSHOT.jar data1 data2 data3

输出结果为:

2017-03-19 16:26:06.952  INFO 5004 --- [           main] c.c.bean.ApplicationRunnerBean           : Application started with arguments:data1|data2|data3
2017-03-19 16:26:06.956 INFO 5004 --- [ main] com.concretepage.MyApplication : Started MyApplication in 1.334 seconds (JVM running for 1.797)
2017-03-19 16:26:06.957 INFO 5004 --- [ main] com.concretepage.MyApplication : Hello World!

CommandLineRunner和ApplicationRunner的执行顺序

在spring boot程序中,我们可以使用不止一个实现CommandLineRunnerApplicationRunner的bean。为了有序执行这些bean的run()方法,可以使用@Order注解或Ordered接口。例子中我们创建了两个实现CommandLineRunner接口的bean和两个实现ApplicationRunner接口的bean。我们使用@Order注解按顺序执行这四个bean。

CommandLineRunnerBean1.java

@Component
@Order(1)
public class CommandLineRunnerBean1 implements CommandLineRunner {
public void run(String... args) {
System.out.println("CommandLineRunnerBean 1");
}
}

ApplicationRunnerBean1.java

@Component
@Order(2)
public class ApplicationRunnerBean1 implements ApplicationRunner {
@Override
public void run(ApplicationArguments arg0) throws Exception {
System.out.println("ApplicationRunnerBean 1");
}
}

CommandLineRunnerBean2.java

@Component
@Order(3)
public class CommandLineRunnerBean2 implements CommandLineRunner {
public void run(String... args) {
System.out.println("CommandLineRunnerBean 2");
}
}

ApplicationRunnerBean2.java

@Component
@Order(4)
public class ApplicationRunnerBean2 implements ApplicationRunner {
@Override
public void run(ApplicationArguments arg0) throws Exception {
System.out.println("ApplicationRunnerBean 2");
}
}

输出结果为:

CommandLineRunnerBean 1
ApplicationRunnerBean 1
CommandLineRunnerBean 2
ApplicationRunnerBean 2

作者:Java_Explorer
链接:https://www.jianshu.com/p/de7b0e124248
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

使用CommandLineRunner或ApplicationRunner接口创建bean的更多相关文章

  1. SpringBoot之CommandLineRunner接口和ApplicationRunner接口

    我们在开发中可能会有这样的情景.需要在容器启动的时候执行一些内容.比如读取配置文件,数据库连接之类的.SpringBoot给我们提供了两个接口来帮助我们实现这种需求.这两个接口分别为CommandLi ...

  2. Spring Boot 2 - 使用CommandLineRunner与ApplicationRunner

    本篇文章我们将探讨CommandLineRunner和ApplicationRunner的使用. 在阅读本篇文章之前,你可以新建一个工程,写一些关于本篇内容代码,这样会加深你对本文内容的理解,关于如何 ...

  3. ApplicationRunner接口

    ApplicationRunner 和 CommandLineRunner 功能一致,用法也基本一致,唯一的区别主要体现在对参数的处理上,ApplicationRunner 可以接收更多类型的参数(A ...

  4. 010-Spring Boot 扩展分析-ApplicationContextInitializer、CommandLineRunner、ApplicationRunner

    一.常见的两个扩展点 1.ApplicationContextInitializer 1.1.作用实现 作用:接口实在Spring容器执行refresh之前的一个回调. Callback interf ...

  5. CommandLineRunner和ApplicationRunner

    使用场景 我们在开发过程中会有这样的场景:需要在容器启动的时候执行一些内容,比如:读取配置文件信息,数据库连接,删除临时文件,清除缓存信息,在Spring框架下是通过ApplicationListen ...

  6. SSH(Struts2+Spring+Hibernate)框架搭建流程<注解的方式创建Bean>

    此篇讲的是MyEclipse9工具提供的支持搭建自加包有代码也是相同:用户登录与注册的例子,表字段只有name,password. SSH,xml方式搭建文章链接地址:http://www.cnblo ...

  7. Spring 学习总结 使用静态工厂创建Bean

    创建Bean时,class属性必须指定,此时为静态工厂类. factory-method指定静态工厂方法名. 接口: public interface Being { public void test ...

  8. Spring工厂方式创建Bean实例

    创建Bean实例的方式: 1) 通过构造器(有参或无参) 方式: <bean id="" class=""/> 2) 通过静态工厂方法 方式: &l ...

  9. Spring Boot 使用Java代码创建Bean并注册到Spring中

    版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/catoop/article/details/50558333 声明同一个类下的多个实例: packa ...

随机推荐

  1. win下使用git-bash工具进行ssh免密登录服务器

    1.ssh-keygen.exe 生成公钥私钥(.pub) 2.ssh-agent.exe bash  指定工具 3.ssh-add.exe   ****   添加私钥 OK

  2. Mysql 之多实例 安装以及配置

    MySQL多实例 1.什么是MySQL多实例 简单地说,Mysql多实例就是在一台服务器上同时开启多个不同的服务端口(3306.3307),同时运行多个Mysql服务进程,这些服务进程通过不同的soc ...

  3. WebView加载失败或网络异常时,替换WebView的错误界面;

    WebView在加载失败时会显示一个失败原因的界面,各个手机显示的界面还都不一样,部分手机还会把Url显示出来:我们要做的就是统一加载失败的界面: 大概思路:在WebView这个控件上面再覆盖一个Vi ...

  4. Android仿淘宝头条滚动广告条

    之前我使用TextView+Handler+动画,实现了一个简单的仿淘宝广告条的滚动,https://download.csdn.net/download/qq_35605213/9660825: 无 ...

  5. vue2.0混入mixins

    假设一个项目,首页不需要登录就可以直接进入,但是在首页中有各种其他的模块,这些模块中,有些需要登录权限,而有些则不需要登录权限,所以在进入这些模块的时候,我们都要判断当前的登录状态,那么我们应该怎么组 ...

  6. 零基础学习python_模块(50-52课)

    今天学了下模块,那什么是模块呢?其实我们写的以py结尾的一个文件就是一个模块,模块也就是程序 还记得我们之前学过容器.函数.类吧 容器    ->    数据的封装 函数    ->   ...

  7. Python下的opencv小问题大智慧

    1.今晚日了狗了,图像显示不按照预期出现,然后突然就好了...... 2.根据第一个问题举一个例子,另一个我没保存... 是不是分不清楚????   plt.imshow(wjy2, cmap='gr ...

  8. UiAutomator 代码记录 : 遍历桌面

    package test_one; import java.lang.*; import java.io.File; import com.android.uiautomator.core.UiDev ...

  9. [Unity插件]Lua行为树(五):装饰节点Repeater

    Repeater:重复执行子节点,直到一定次数 特点如下: 1.执行次数可以是无限循环,也可以是固定次数 2.一般来说,子节点的执行返回状态不会影响Repeater节点,但可以设置当子节点返回失败时, ...

  10. 2、申请苹果App ID

    在“iOS Certificates”页面“Identifiers"下选择“App IDs",可查看到已申请的所有App ID,点击右上角的加号可创建新“App ID”:打开“Re ...