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.gifbanner.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

${application.version}


The version number of your application as declared in MANIFEST.MF. For exampleImplementation-Version: 1.0 is printed as 1.0.


${application.formatted-version}


The version number of your application as declared in MANIFEST.MF formatted for display (surrounded with brackets and prefixed with v). For example (v1.0).


${spring-boot.version}


The Spring Boot version that you are using. For example 1.4.0.RELEASE.


${spring-boot.formatted-version}


The Spring Boot version that you are using formatted for display (surrounded with brackets and prefixed with v). For example (v1.4.0.RELEASE).


${Ansi.NAME} (or ${AnsiColor.NAME},${AnsiBackground.NAME}${AnsiStyle.NAME})


Where NAME is the name of an ANSI escape code. See AnsiPropertySource for details.


${application.title}


The title of your application as declared in MANIFEST.MF. For exampleImplementation-Title: MyApp is printed as MyApp.


The SpringApplication.setBanner(…​) method can be used if you want to generate a banner programmatically. Use theorg.springframework.boot.Banner interface and implement your own printBanner() method.

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 off to false so make sure to add quotes if you want to disable the banner in your application.

spring:
    main:
        banner-mode: "off"

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 SpringApplication are configuration sources for spring beans. In most cases these will be references to@Configuration classes, but they could also be references to XML configuration or to packages that should be scanned.

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 ApplicationContext hierarchy, e.g. Web components must be contained within the child context, and the same Environment will be used for both parent and child contexts. See the SpringApplicationBuilder Javadoc for full details.

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 ApplicationContext is created so you cannot register a listener on those as a @Bean. You can register them via the SpringApplication.addListeners(…​) or SpringApplicationBuilder.listeners(…​) methods.

If you want those listeners to be registered automatically regardless of the way the application is created you can add a META-INF/spring.factories file to your project and reference your listener(s) using the org.springframework.context.ApplicationListener key.

org.springframework.context.ApplicationListener=com.example.project.MyListener

Application events are sent in the following order, as your application runs:

  1. An ApplicationStartedEvent is sent at the start of a run, but before any processing except the registration of listeners and initializers.
  2. An ApplicationEnvironmentPreparedEvent is sent when the Environment to be used in the context is known, but before the context is created.
  3. An ApplicationPreparedEvent is sent just before the refresh is started, but after bean definitions have been loaded.
  4. An ApplicationReadyEvent is sent after the refresh and any related callbacks have been processed to indicate the application is ready to service requests.
  5. An ApplicationFailedEvent is 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

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 setWebEnvironment(false) when using SpringApplication within a JUnit test.

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 CommandLinePropertySource with the Spring Environment. This allows you to also inject single application arguments using the @Value annotation.

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 local.server.port.


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

时间: 2024-10-29 19:03:29

Spring Boot 启动加载数据 CommandLineRunner的相关文章

Spring Boot 自动加载指定包下的拦截器

Spring Boot 在我们需要对程序添加拦截器需要使用 WebMvcConfigurerAdapter 中的 addInterceptors方法去注册拦截器,这样我们如果在程序里面有多个拦截或者我们在项目结构为maven 关系存在父子级关系时候.WebMvcConfigurerAdapter 类我们写在父类 这样就无法获取到子类存在哪些拦截器了.这个我们就需要在父级和子级都写对应的 WebMvcConfigurerAdapter 方法.这里我根据前面我的一篇博客为 获取某个包下面的所有类来实

spring集成velocity,项目启动加载不到vm页面是为什么?

问题描述 spring集成velocity,项目启动加载不到vm页面是为什么? 这是在spring_mvc中的配置: <bean class="org.springframework.web.servlet.view.ResourceBundleViewResolver"> <property name="basename" value="views"></property> </bean> <

spring mvc easyui 中tree如何加载数据

问题描述 spring mvc easyui 中tree如何加载数据 easyUI tree如何加载spring mvc 传过来的数据,..也不知道传过来没有 解决方案 就这样写可以了,还是其它什么意思? $('#tt').tree({ url:'/...' // Spring MVC 请求的地址 }); 解决方案二: 已经解决了,原来直接返回数据时还需要一个@responseBody的注解. 不过还是非常感谢

pring easyui-Spring MVC easyui1.3.2 datagrid无法加载数据

问题描述 Spring MVC easyui1.3.2 datagrid无法加载数据 jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@include file="/common/page/jqueryMaster.jsp"%> <!DOCTYPE html P

Bootstrap Table从服务器加载数据进行显示的实现方法_javascript技巧

Bootstrap-Table是一个Boostrap的表格插件,能够将JSON数据直接显示在表格中.当然,这需要配置一些参数并进行初始化表格才行.其官方网站地址为:http://bootstrap-table.wenzhixin.net.cn/.里面可以下载使用所需的JS和CSS文件,以及参考文档和例子.         Bootstrap-Table显示数据到表格的方式有两种,一种是客户端(client)模式,一种是服务器(server)模式.         所谓客户端模式,指的是在服务器中

Java 并发专题 :FutureTask 实现预加载数据 在线看电子书、浏览器浏览网页等

转自:http://blog.csdn.net/lmj623565791/article/details/26817403  继续并发专题~ FutureTask 有点类似Runnable,都可以通过Thread来启动,不过FutureTask可以返回执行完毕的数据,并且FutureTask的get方法支持阻塞. 由于:FutureTask可以返回执行完毕的数据,并且FutureTask的get方法支持阻塞这两个特性,我们可以用来预先加载一些可能用到资源,然后要用的时候,调用get方法获取(如果

Android实现listview动态加载数据分页的两种方法_Android

在android开发中,经常需要使用数据分页,比如要实现一个新闻列表的显示,或者博文列表的显示,不可能第一次加载就展示出全部,这就需要使用分页的方法来加载数据,在android中Handler经常用来在耗时的工作中,它接收子线程发送的数据,并使用数据配合更新UI,AsyncTask是在一个线程中执行耗时操作然后把结果传给UI线程,不需要你亲自去管理线程和句柄. 一.使用Handler+线程方法1.基础知识Handler在android系统中,主要负责发送和接收消息,它的用途主要有以下两种: (1

《Hadoop实战手册》一1.11 利用Flume加载数据到HDFS中

1.11 利用Flume加载数据到HDFS中 Apache Flume是Hadoop社区的一个项目,由多个相关项目组成,用于从不同的数据源可靠有效地加载数据流到HDFS中.Flume最常见的一个场景是加载多个数据源的网站日志数据.本节将介绍如何使用Flume加载数据到HDFS中. 准备工作在本节中假定你已经安装和配置好Flume. Flume可以从Apache网页(http://incubator.apache.org/flume/)下载. 如果你使用的是CDH3,那么默认已经安装了Flume

DWR Ext 加载数据_extjs

一,在Ext中直接使用DWR 1,PoJO的Manager类为 复制代码 代码如下: public class CustomerManagerImpl extends HibernateDaoSupport implements CustomerManager { public PageModel allCustomers() { PageModel pageModel = new PageModel(); List datas = new ArrayList(); int total ; St