Spring Boot 启动加载数据 CommandLineRunner
实际应用中,我们会有在项目服务启动的时候就去加载一些数据或做一些事情这样的需求。
为了解决这样的问题,Spring Boot 为我们提供了一个方法,通过实现接口 CommandLineRunner 来实现。
很简单,只需要一个类就可以,无需其他配置。
创建实现接口 CommandLineRunner 的类
package org.springboot.sample.runner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
/**
* 服务启动执行
*
* @author 单红宇(365384722)
* @myblog http://blog.csdn.net/catoop/
* @create 2016年1月9日
*/
@Component
public class MyStartupRunner1 implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println(">>>>>>>>>>>>>>>服务启动执行,执行加载数据等操作<<<<<<<<<<<<<");
}
}
Spring Boot应用程序在启动后,会遍历CommandLineRunner接口的实例并运行它们的run方法。也可以利用@Order注解(或者实现Order接口)来规定所有CommandLineRunner实例的运行顺序。
如下我们使用@Order 注解来定义执行顺序。
package org.springboot.sample.runner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
/**
* 服务启动执行
*
* @author 单红宇(365384722)
* @myblog http://blog.csdn.net/catoop/
* @create 2016年1月9日
*/
@Component
@Order(value=2)
public class MyStartupRunner1 implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println(">>>>>>>>>>>>>>>服务启动执行,执行加载数据等操作 11111111 <<<<<<<<<<<<<");
}
}
package org.springboot.sample.runner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
/**
* 服务启动执行
*
* @author 单红宇(365384722)
* @myblog http://blog.csdn.net/catoop/
* @create 2016年1月9日
*/
@Component
@Order(value=1)
public class MyStartupRunner2 implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println(">>>>>>>>>>>>>>>服务启动执行,执行加载数据等操作 22222222 <<<<<<<<<<<<<");
}
}
启动程序后,控制台输出结果为:
>>>>>>>>>>>>>>>服务启动执行,执行加载数据等操作 22222222 <<<<<<<<<<<<<
>>>>>>>>>>>>>>>服务启动执行,执行加载数据等操作 11111111 <<<<<<<<<<<<<
根据控制台结果可判断,@Order 注解的执行优先级是按value值从小到大顺序。
http://blog.csdn.net/catoop/article/details/50501710
eclipse中给java应用传args参数的方法如下:
1、先写好Java代码,比如文件名为IntArrqy.java;
2、在工具栏或菜单上点run as下边有个Run Configuration;
3、在弹出窗口点选第二个标签arguments;
4、把你想输入的参数写在program argumenst就可以了,多个参数使用空格隔开。
完成后点run即可通过运行结果看到参数使用情况了。
23. SpringApplication
The SpringApplication class provides a convenient way to bootstrap a Spring application that will be started from a main() method. In many situations you can just delegate to the static SpringApplication.run method:
public static void main(String[] args) {
SpringApplication.run(MySpringConfiguration.class, args);
}
When your application starts you should see something similar to the following:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: v1.4.0.RELEASE 2013-07-31 00:08:16.117 INFO 56603 --- [ main] o.s.b.s.app.SampleApplication : Starting SampleApplication v0.1.0 on mycomputer with PID 56603 (/apps/myapp.jar started by pwebb)
2013-07-31 00:08:16.166 INFO 56603 --- [ main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@6e5a8246: startup date [Wed Jul 31 00:08:16 PDT 2013]; root of context hierarchy
2014-03-04 13:09:54.912 INFO 41370 --- [ main] .t.TomcatEmbeddedServletContainerFactory : Server initialized with port: 8080
2014-03-04 13:09:56.501 INFO 41370 --- [ main] o.s.b.s.app.SampleApplication : Started SampleApplication in 2.992 seconds (JVM running for 3.658)
By default INFO logging messages will be shown, including some relevant startup details such as the user that launched the application.
23.1 Customizing the Banner
The banner that is printed on start up can be changed by adding a banner.txt file to your classpath, or by setting banner.location to the location of such a file. If the file has an unusual encoding you can set banner.charset (default is UTF-8). In addition to a text file, you can also add a banner.gif, banner.jpg orbanner.png image file to your classpath, or set a banner.image.location property. Images will be converted into an ASCII art representation and printed above any text banner.
Inside your banner.txt file you can use any of the following placeholders:
Table 23.1. Banner variables
| Variable | Description |
|---|---|
|
|
The version number of your application as declared in |
|
|
The version number of your application as declared in |
|
|
The Spring Boot version that you are using. For example |
|
|
The Spring Boot version that you are using formatted for display (surrounded with brackets and prefixed with |
|
|
Where |
|
|
The title of your application as declared in |
![]() |
|
The |
You can also use the spring.main.banner-mode property to determine if the banner has to be printed on System.out (console), using the configured logger (log) or not at all (off).
The printed banner will be registered as a singleton bean under the name springBootBanner.
![]() |
|
YAML maps spring: |
23.2 Customizing SpringApplication
If the SpringApplication defaults aren’t to your taste you can instead create a local instance and customize it. For example, to turn off the banner you would write:
public static void main(String[] args) {
SpringApplication app = new SpringApplication(MySpringConfiguration.class);
app.setBannerMode(Banner.Mode.OFF);
app.run(args);
}
![]() |
|
The constructor arguments passed to |
It is also possible to configure the SpringApplication using an application.properties file. See Chapter 24, Externalized Configuration for details.
For a complete list of the configuration options, see the SpringApplication Javadoc.
23.3 Fluent builder API
If you need to build an ApplicationContext hierarchy (multiple contexts with a parent/child relationship), or if you just prefer using a ‘fluent’ builder API, you can use the SpringApplicationBuilder.
The SpringApplicationBuilder allows you to chain together multiple method calls, and includes parent and child methods that allow you to create a hierarchy.
For example:
new SpringApplicationBuilder()
.bannerMode(Banner.Mode.OFF)
.sources(Parent.class)
.child(Application.class)
.run(args);
![]() |
|
There are some restrictions when creating an |
23.4 Application events and listeners
In addition to the usual Spring Framework events, such as ContextRefreshedEvent, a SpringApplication sends some additional application events.
![]() |
|
Some events are actually triggered before the If you want those listeners to be registered automatically regardless of the way the application is created you can add a org.springframework.context.ApplicationListener=com.example.project.MyListener |
Application events are sent in the following order, as your application runs:
- An
ApplicationStartedEventis sent at the start of a run, but before any processing except the registration of listeners and initializers. - An
ApplicationEnvironmentPreparedEventis sent when theEnvironmentto be used in the context is known, but before the context is created. - An
ApplicationPreparedEventis sent just before the refresh is started, but after bean definitions have been loaded. - An
ApplicationReadyEventis sent after the refresh and any related callbacks have been processed to indicate the application is ready to service requests. - An
ApplicationFailedEventis sent if there is an exception on startup.
![]() |
|
You often won’t need to use application events, but it can be handy to know that they exist. Internally, Spring Boot uses events to handle a variety of tasks. |
23.5 Web environment
A SpringApplication will attempt to create the right type of ApplicationContext on your behalf. By default, an AnnotationConfigApplicationContext orAnnotationConfigEmbeddedWebApplicationContext will be used, depending on whether you are developing a web application or not.
The algorithm used to determine a ‘web environment’ is fairly simplistic (based on the presence of a few classes). You can usesetWebEnvironment(boolean webEnvironment) if you need to override the default.
It is also possible to take complete control of the ApplicationContext type that will be used by calling setApplicationContextClass(…).
![]() |
|
It is often desirable to call |
23.6 Accessing application arguments
If you need to access the application arguments that were passed to SpringApplication.run(…) you can inject aorg.springframework.boot.ApplicationArguments bean. The ApplicationArguments interface provides access to both the raw String[] arguments as well as parsed option and non-option arguments:
import org.springframework.boot.*
import org.springframework.beans.factory.annotation.*
import org.springframework.stereotype.* @Component
public class MyBean { @Autowired
public MyBean(ApplicationArguments args) {
boolean debug = args.containsOption("debug");
List<String> files = args.getNonOptionArgs();
// if run with "--debug logfile.txt" debug=true, files=["logfile.txt"]
} }
![]() |
|
Spring Boot will also register a |
23.7 Using the ApplicationRunner or CommandLineRunner
If you need to run some specific code once the SpringApplication has started, you can implement the ApplicationRunner or CommandLineRunner interfaces. Both interfaces work in the same way and offer a single run method which will be called just before SpringApplication.run(…) completes.
The CommandLineRunner interfaces provides access to application arguments as a simple string array, whereas the ApplicationRunner uses theApplicationArguments interface discussed above.
import org.springframework.boot.*
import org.springframework.stereotype.* @Component
public class MyBean implements CommandLineRunner { public void run(String... args) {
// Do something...
} }
You can additionally implement the org.springframework.core.Ordered interface or use the org.springframework.core.annotation.Order annotation if several CommandLineRunner or ApplicationRunner beans are defined that must be called in a specific order.

23.8 Application exit
Each SpringApplication will register a shutdown hook with the JVM to ensure that the ApplicationContext is closed gracefully on exit. All the standard Spring lifecycle callbacks (such as the DisposableBean interface, or the @PreDestroy annotation) can be used.
In addition, beans may implement the org.springframework.boot.ExitCodeGenerator interface if they wish to return a specific exit code when the application ends.
23.9 Admin features
It is possible to enable admin-related features for the application by specifying the spring.application.admin.enabled property. This exposes theSpringApplicationAdminMXBean on the platform MBeanServer. You could use this feature to administer your Spring Boot application remotely. This could also be useful for any service wrapper implementation.
![]() |
|
If you want to know on which HTTP port the application is running, get the property with key |
![]() |
|
Take care when enabling this feature as the MBean exposes a method to shutdown the application. |
http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-spring-application.html
Spring Boot 启动加载数据 CommandLineRunner的更多相关文章
- 十三、 Spring Boot 启动加载数据 CommandLineRunner
实际应用中,我们会有在项目服务启动的时候就去加载一些数据或做一些事情这样的需求. 为了解决这样的问题,spring Boot 为我们提供了一个方法,通过实现接口 CommandLineRunner 来 ...
- 23. Spring Boot启动加载数据CommandLineRunner【从零开始学Spring Boot】
转:http://blog.csdn.net/linxingliang/article/details/52069503 实际应用中,我们会有在项目服务启动的时候就去加载一些数据或做一些事情这样的需求 ...
- (23)Spring Boot启动加载数据CommandLineRunner【从零开始学Spring Boot】
[Spring Boot 系列博客] )前言[从零开始学Spring Boot] : http://412887952-qq-com.iteye.com/blog/2291496 )spring bo ...
- 7. Spring Boot 启动加载数据 CommandLineRunner
转自:https://blog.csdn.net/catoop/article/details/50501710
- spring boot启动加载项CommandLineRunner
spring boot启动加载项CommandLineRunner 在使用SpringBoot构建项目时,我们通常有一些预先数据的加载.那么SpringBoot提供了一个简单的方式来实现–Comman ...
- spring boot启动加载数据
实际应用中,我们会有在项目服务启动的时候就去加载一些数据或做一些事情这样的需求.为了解决这样的问题,spring Boot 为我们提供了一个方法,通过实现接口 CommandLineRunner 来实 ...
- 在Spring Boot中加载初始化数据
文章目录 依赖条件 data.sql文件 schema.sql 文件 @sql注解 @SqlConfig 注解 在Spring Boot中加载初始化数据 在Spring Boot中,Spring Bo ...
- SpringBoot(七)-- 启动加载数据
一.场景 实际应用中,我们会有在项目服务启动的时候就去加载一些数据或做一些事情这样的需求.为了解决这样的问题,spring Boot 为我们提供了一个方法,通过实现接口 CommandLineRunn ...
- [十五]SpringBoot 之 启动加载数据
实际应用中,我们会有在项目服务启动的时候就去加载一些数据或做一些事情这样的需求. 为了解决这样的问题,spring Boot 为我们提供了一个方法,通过实现接口 CommandLineRunner 来 ...
随机推荐
- Why Memory Barrier?
引言:xchg做了什么? 首先,xchg eax, ecx并不会比mov edx, eax + mov eax, ecx + mov ecx, edx这三条指令加一起快,原因是xchg有副作用. Mi ...
- python 操作 office
首先介绍下office win32 com接口,这个是MS为自动化提供的操作接口,比如我们打开一个WORD文档,就可以在里面编辑VB脚本,实现我们自己的效果.对于这种一本万利的买卖,Python怎么能 ...
- Putty server refused our key的解决方法
在使用putty工具使用密钥远程登陆CentOS系统时,出现Putty server refused our key提示,解决办法: 1.查看是否关掉SELINUX. 相关命令:getenforce, ...
- android面试题之六
三十一.AIDL的全称是什么?如何工作?能处理哪些类型的数据? 英文全称:Android Interface Define Language(Android接口定义语言). 当A进程要去调用B进程中的 ...
- 获取java类和方法名
String clazz = this.getClass().getName(); String method = Thread.currentThread() .getStackTrace()[1] ...
- HTML浅识
HTML相关======= ## 认识网页 *web标准(w3c三种标准):结构标准 -->html 表现标准 -->css 行为标准 -->js **浏览器和服务器:浏览器发送报文 ...
- 如何在android上去控制开发进度
这次android的壁纸软件1.0版本终于可以上线了,软件的功能基本上实现了,但是用户体验不太好.在整个开发阶段和测试阶段,出现了很多预料之外的事情,比如size是1M多的json文件解析.高清图片导 ...
- 支持多QQ登录的软件
支持多QQ登录,批量加好友,批量回复QQ消息,当然也能接收 下载链接:多QQ登录软件
- Error when launching Quest Central for DB2: "QCC10000E - Unable to allocate environment handle fo
标题 Error when launching Quest Central for DB2: "QCC10000E - Unable to allocate environment hand ...
- Curl命令使用方法
Curl是Linux下一个很强大的http命令行工具,其功能十分强大.1) 读取网页$ curl http://www.linuxidc.com2) 保存网页$ curl http://www.lin ...

