Spring Boot 启动时执行特殊的代码使用CommandLineRunner、ApplicationRunner

<strong>/*
 * Copyright 2012-2015 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.boot;

import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

/**
 * Interface used to indicate that a bean should <em>run</em> when it is contained within
 * a {@link SpringApplication}. Multiple {@link CommandLineRunner} beans can be defined
 * within the same application context and can be ordered using the {@link Ordered}
 * interface or {@link Order @Order} annotation.
 * <p>
 * If you need access to {@link ApplicationArguments} instead of the raw String array
 * consider using {@link ApplicationRunner}.
 *
 * @author Dave Syer
 * @see ApplicationRunner
 */
public interface CommandLineRunner {

	/**
	 * Callback used to run the bean.
	 * @param args incoming main method arguments
	 * @throws Exception on error
	 */
	void run(String... args) throws Exception;

}
</strong>
操作示例1:打印语句
<strong>import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
 * 项目启动器
 * @author wangbowen
 *
 */
@SpringBootApplication//必须标注该注解才能扫描程序里面的注解组件
public class SimpleApplication  implements CommandLineRunner{

	@Override
	public void run(String... args) throws Exception {
		System.out.println("hello!Spring Boot");
	}

	public static void main(String[] args) {
		SpringApplication.run(SimpleApplication.class, args);
	}
}</strong>
控制台显示信息:

<strong>SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/D:/development%20tools/maven/maven_repertory/ch/qos/logback/logback-classic/1.1.3/logback-classic-1.1.3.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/D:/development%20tools/maven/maven_repertory/org/slf4j/slf4j-log4j12/1.7.13/slf4j-log4j12-1.7.13.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [ch.qos.logback.classic.util.ContextSelectorStaticBinder]

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

2016-01-28 11:01:33.763  INFO 6208 --- [           main] com.my.data.cache.SimpleApplication      : Starting SimpleApplication on wangbowen with PID 6208 (E:\workspace\eclipse_my\com-my-data-cache\target\classes started by Administrator in E:\workspace\eclipse_my\com-my-data-cache)
2016-01-28 11:01:33.764  INFO 6208 --- [           main] com.my.data.cache.SimpleApplication      : No active profile set, falling back to default profiles: default
2016-01-28 11:01:34.216  INFO 6208 --- [           main] ationConfigEmbeddedWebApplicationContext : Refreshing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@11094e7: startup date [Thu Jan 28 11:01:34 CST 2016]; root of context hierarchy
2016-01-28 11:01:36.626  INFO 6208 --- [           main] o.s.b.f.s.DefaultListableBeanFactory     : Overriding bean definition for bean 'beanNameViewResolver' with a different definition: replacing [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/ErrorMvcAutoConfiguration$WhitelabelErrorViewConfiguration.class]] with [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter; factoryMethodName=beanNameViewResolver; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/WebMvcAutoConfiguration$WebMvcAutoConfigurationAdapter.class]]
2016-01-28 11:01:37.794  INFO 6208 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [class org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$96fb5b46] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2016-01-28 11:01:38.135  INFO 6208 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cache.annotation.ProxyCachingConfiguration' of type [class org.springframework.cache.annotation.ProxyCachingConfiguration$$EnhancerBySpringCGLIB$$fe5925a4] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2016-01-28 11:01:38.191  INFO 6208 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration' of type [class org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration$$EnhancerBySpringCGLIB$$388125c8] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2016-01-28 11:01:38.457  INFO 6208 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'spring.cache.CONFIGURATION_PROPERTIES' of type [class org.springframework.boot.autoconfigure.cache.CacheProperties] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2016-01-28 11:01:38.471  INFO 6208 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.boot.autoconfigure.cache.SimpleCacheConfiguration' of type [class org.springframework.boot.autoconfigure.cache.SimpleCacheConfiguration$$EnhancerBySpringCGLIB$$c83bd089] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2016-01-28 11:01:38.487  INFO 6208 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'cacheManager' of type [class org.springframework.cache.concurrent.ConcurrentMapCacheManager] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2016-01-28 11:01:38.491  INFO 6208 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'cacheAutoConfigurationValidator' of type [class org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration$CacheManagerValidator] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2016-01-28 11:01:39.199  INFO 6208 --- [           main] e.j.JettyEmbeddedServletContainerFactory : Server initialized with port: 8080
2016-01-28 11:01:39.204  INFO 6208 --- [           main] org.eclipse.jetty.server.Server          : jetty-9.2.14.v20151106
2016-01-28 11:01:39.396  INFO 6208 --- [           main] application                              : Initializing Spring embedded WebApplicationContext
2016-01-28 11:01:39.396  INFO 6208 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 5181 ms
2016-01-28 11:01:40.557  INFO 6208 --- [           main] o.s.b.c.e.ServletRegistrationBean        : Mapping servlet: 'dispatcherServlet' to [/]
2016-01-28 11:01:40.568  INFO 6208 --- [           main] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'characterEncodingFilter' to: [/*]
2016-01-28 11:01:40.568  INFO 6208 --- [           main] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2016-01-28 11:01:40.569  INFO 6208 --- [           main] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'httpPutFormContentFilter' to: [/*]
2016-01-28 11:01:40.569  INFO 6208 --- [           main] o.s.b.c.embedded.FilterRegistrationBean  : Mapping filter: 'requestContextFilter' to: [/*]
2016-01-28 11:01:40.912  INFO 6208 --- [           main] o.e.jetty.server.handler.ContextHandler  : Started o.s.b.c.e.j.JettyEmbeddedWebAppContext@fc596e{/,file:/C:/Users/Administrator/AppData/Local/Temp/jetty-docbase.7392717449312476338.8080/,AVAILABLE}
2016-01-28 11:01:40.913  INFO 6208 --- [           main] org.eclipse.jetty.server.Server          : Started @8944ms
2016-01-28 11:01:42.660  INFO 6208 --- [           main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2016-01-28 11:01:42.677  INFO 6208 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
	name: default
	...]
2016-01-28 11:01:42.861  INFO 6208 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate Core {4.3.11.Final}
2016-01-28 11:01:42.864  INFO 6208 --- [           main] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2016-01-28 11:01:42.867  INFO 6208 --- [           main] org.hibernate.cfg.Environment            : HHH000021: Bytecode provider name : javassist
2016-01-28 11:01:43.522  INFO 6208 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
2016-01-28 11:01:43.653  INFO 6208 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2016-01-28 11:01:43.890  INFO 6208 --- [           main] o.h.h.i.ast.ASTQueryTranslatorFactory    : HHH000397: Using ASTQueryTranslatorFactory
2016-01-28 11:01:45.688  INFO 6208 --- [           main] c.m.d.cache.config.MyWebAppConfigurer    : >>>>>>D:\Program Files\Java\jdk1.7.0_13>>>>>>
2016-01-28 11:01:45.689  INFO 6208 --- [           main] c.m.d.cache.config.MyWebAppConfigurer    : >>>>>>jdbc:mysql://localhost/mydatabase<<<<<<<<
2016-01-28 11:01:45.689  INFO 6208 --- [           main] c.m.d.cache.config.MyWebAppConfigurer    : jdbc:mysql://localhost/mydatabase
2016-01-28 11:01:47.866  INFO 6208 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@11094e7: startup date [Thu Jan 28 11:01:34 CST 2016]; root of context hierarchy
2016-01-28 11:01:48.489  INFO 6208 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/book/add]}" onto public java.lang.String com.my.data.cache.controller.BookController.insertBook()
2016-01-28 11:01:48.491  INFO 6208 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/book/list],methods=[GET]}" onto public java.util.List<com.my.data.cache.domain.Book> com.my.data.cache.controller.BookController.list()
2016-01-28 11:01:48.492  INFO 6208 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/book/{id}]}" onto public com.my.data.cache.domain.Book com.my.data.cache.controller.BookController.index(java.lang.Integer)
2016-01-28 11:01:48.492  INFO 6208 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/book/update]}" onto public java.lang.String com.my.data.cache.controller.BookController.update()
2016-01-28 11:01:48.493  INFO 6208 --- [           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)
2016-01-28 11:01:48.493  INFO 6208 --- [           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)
2016-01-28 11:01:48.591  INFO 6208 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-01-28 11:01:48.591  INFO 6208 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-01-28 11:01:48.718  INFO 6208 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-01-28 11:01:48.846  WARN 6208 --- [           main] o.s.b.a.t.ThymeleafAutoConfiguration     : Cannot find template location: classpath:/templates/ (please add some templates or check your Thymeleaf configuration)
2016-01-28 11:01:50.786  INFO 6208 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2016-01-28 11:01:50.850  INFO 6208 --- [           main] application                              : Initializing Spring FrameworkServlet 'dispatcherServlet'
2016-01-28 11:01:50.850  INFO 6208 --- [           main] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization started
2016-01-28 11:01:50.927  INFO 6208 --- [           main] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 77 ms
2016-01-28 11:01:51.120  INFO 6208 --- [           main] o.eclipse.jetty.server.ServerConnector   : Started ServerConnector@125130d{HTTP/1.1}{0.0.0.0:8080}
2016-01-28 11:01:51.132  INFO 6208 --- [           main] .s.b.c.e.j.JettyEmbeddedServletContainer : Jetty started on port(s) 8080 (http/1.1)
<span style="color:#ff0000;">hello!Spring Boot</span></strong>
操作示例二:调用接口

<strong>import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

import com.my.data.cache.domain.Book;
import com.my.data.cache.service.BookService;


/**
 * 
 * 启动器
 *
 */
@SpringBootApplication
@EnableCaching//扫描cahce注解
public class Application1  implements CommandLineRunner{
	
	@Autowired
    private BookService bookService;
	@Override
	public void run(String... args) throws Exception {
		Book b1 = bookService.findByIsbn("1");
		Book b2 = bookService.findByIsbn("2");
		Book b3 = bookService.findById(3);
	    System.out.println(b1);
        System.out.println(b2);
        System.out.println(b3);
		
	}
	public static void main(String[] args) {
		 SpringApplication.run(Application1.class,args);
	}

}</strong>
控制台信息:
<strong>2016-01-28 11:05:49.996  INFO 8536 --- [           main] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2016-01-28 11:05:50.000  INFO 8536 --- [           main] org.hibernate.cfg.Environment            : HHH000021: Bytecode provider name : javassist
2016-01-28 11:05:50.489  INFO 8536 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {4.0.5.Final}
2016-01-28 11:05:50.626  INFO 8536 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
2016-01-28 11:05:50.889  INFO 8536 --- [           main] o.h.h.i.ast.ASTQueryTranslatorFactory    : HHH000397: Using ASTQueryTranslatorFactory
2016-01-28 11:05:52.791  INFO 8536 --- [           main] c.m.d.cache.config.MyWebAppConfigurer    : >>>>>>D:\Program Files\Java\jdk1.7.0_13>>>>>>
2016-01-28 11:05:52.791  INFO 8536 --- [           main] c.m.d.cache.config.MyWebAppConfigurer    : >>>>>>jdbc:mysql://localhost/mydatabase<<<<<<<<
2016-01-28 11:05:52.792  INFO 8536 --- [           main] c.m.d.cache.config.MyWebAppConfigurer    : jdbc:mysql://localhost/mydatabase
2016-01-28 11:05:53.359  INFO 8536 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@1e48a4f: startup date [Thu Jan 28 11:05:40 CST 2016]; root of context hierarchy
2016-01-28 11:05:53.558  INFO 8536 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/book/add]}" onto public java.lang.String com.my.data.cache.controller.BookController.insertBook()
2016-01-28 11:05:53.560  INFO 8536 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/book/list],methods=[GET]}" onto public java.util.List<com.my.data.cache.domain.Book> com.my.data.cache.controller.BookController.list()
2016-01-28 11:05:53.561  INFO 8536 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/book/{id}]}" onto public com.my.data.cache.domain.Book com.my.data.cache.controller.BookController.index(java.lang.Integer)
2016-01-28 11:05:53.561  INFO 8536 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/book/update]}" onto public java.lang.String com.my.data.cache.controller.BookController.update()
2016-01-28 11:05:53.568  INFO 8536 --- [           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)
2016-01-28 11:05:53.568  INFO 8536 --- [           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)
2016-01-28 11:05:53.682  INFO 8536 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-01-28 11:05:53.682  INFO 8536 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-01-28 11:05:53.831  INFO 8536 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2016-01-28 11:05:54.028  WARN 8536 --- [           main] o.s.b.a.t.ThymeleafAutoConfiguration     : Cannot find template location: classpath:/templates/ (please add some templates or check your Thymeleaf configuration)
2016-01-28 11:05:55.526  INFO 8536 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2016-01-28 11:05:55.563  INFO 8536 --- [           main] application                              : Initializing Spring FrameworkServlet 'dispatcherServlet'
2016-01-28 11:05:55.563  INFO 8536 --- [           main] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization started
2016-01-28 11:05:55.611  INFO 8536 --- [           main] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 48 ms
2016-01-28 11:05:55.688  INFO 8536 --- [           main] o.eclipse.jetty.server.ServerConnector   : Started ServerConnector@160ba79{HTTP/1.1}{0.0.0.0:8080}
2016-01-28 11:05:55.694  INFO 8536 --- [           main] .s.b.c.e.j.JettyEmbeddedServletContainer : Jetty started on port(s) 8080 (http/1.1)
Hibernate: select book0_.id as id1_0_, book0_.isbn as isbn2_0_, book0_.title as title3_0_ from book book0_ where book0_.isbn=?
Hibernate: select book0_.id as id1_0_, book0_.isbn as isbn2_0_, book0_.title as title3_0_ from book book0_ where book0_.isbn=?
Hibernate: select book0_.id as id1_0_, book0_.isbn as isbn2_0_, book0_.title as title3_0_ from book book0_ where book0_.id=?
Book{isbn='1', title='爱的力量'}
Book{isbn='2', title='呵呵'}
Book{isbn='1111', title='相信自己'}
hello!Spring Boot
2016-01-28 11:06:00.955  INFO 8536 --- [           main] com.my.data.cache.Application1  </strong>


ApplicationRunner
<strong>/*
 * Copyright 2012-2015 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.boot;

import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

/**
 * Interface used to indicate that a bean should <em>run</em> when it is contained within
 * a {@link SpringApplication}. Multiple {@link ApplicationRunner} beans can be defined
 * within the same application context and can be ordered using the {@link Ordered}
 * interface or {@link Order @Order} annotation.
 *
 * @author Phillip Webb
 * @since 1.3.0
 * @see CommandLineRunner
 */
public interface ApplicationRunner {

	/**
	 * Callback used to run the bean.
	 * @param args incoming application arguments
	 * @throws Exception on error
	 */
	void run(ApplicationArguments args) throws Exception;

}
</strong>

package com.my.data.cache;

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
 * 项目启动器
 * @author wangbowen
 *
 */
@SpringBootApplication//必须标注该注解才能扫描程序里面的注解组件
public class SimpleApplication  implements ApplicationRunner{


	public static void main(String[] args) {
		SpringApplication.run(SimpleApplication.class, args);
	}

	@Override
	public void run(ApplicationArguments args) throws Exception {
		System.out.println("-------------"+args);
	}
}

示例3:
package com.my.data.cache.domain;

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class Mybean  implements CommandLineRunner{
   
	@Override
	public void run(String... args) throws Exception {
		System.out.println("程序员的苦逼生活!!!");
	}

}

控制台信息:
2016-01-28 11:17:55.223  INFO 10064 --- [           main] application                              : Initializing Spring FrameworkServlet 'dispatcherServlet'
2016-01-28 11:17:55.223  INFO 10064 --- [           main] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization started
2016-01-28 11:17:55.296  INFO 10064 --- [           main] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 73 ms
2016-01-28 11:17:55.464  INFO 10064 --- [           main] o.eclipse.jetty.server.ServerConnector   : Started ServerConnector@820067{HTTP/1.1}{0.0.0.0:8080}
2016-01-28 11:17:55.484  INFO 10064 --- [           main] .s.b.c.e.j.JettyEmbeddedServletContainer : Jetty started on port(s) 8080 (http/1.1)
hello!Spring Boot
Hibernate: select book0_.id as id1_0_, book0_.isbn as isbn2_0_, book0_.title as title3_0_ from book book0_ where book0_.isbn=?
Hibernate: select book0_.id as id1_0_, book0_.isbn as isbn2_0_, book0_.title as title3_0_ from book book0_ where book0_.isbn=?
Hibernate: select book0_.id as id1_0_, book0_.isbn as isbn2_0_, book0_.title as title3_0_ from book book0_ where book0_.id=?
Book{isbn='1', title='爱的力量'}
Book{isbn='2', title='呵呵'}
Book{isbn='1111', title='相信自己'}
程序员的苦逼生活!!!




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值