010-Spring Boot 扩展分析-ApplicationContextInitializer、CommandLineRunner、ApplicationRunner
一、常见的两个扩展点
1、ApplicationContextInitializer
1.1、作用实现
作用:接口实在Spring容器执行refresh之前的一个回调。
Callback interface for initializing a Spring {@link ConfigurableApplicationContext}
实现:
/*
* Copyright 2002-2011 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.context; /**
* Callback interface for initializing a Spring {@link ConfigurableApplicationContext}
* prior to being {@linkplain ConfigurableApplicationContext#refresh() refreshed}.
*
* <p>Typically used within web applications that require some programmatic initialization
* of the application context. For example, registering property sources or activating
* profiles against the {@linkplain ConfigurableApplicationContext#getEnvironment()
* context's environment}. See {@code ContextLoader} and {@code FrameworkServlet} support
* for declaring a "contextInitializerClasses" context-param and init-param, respectively.
*
* <p>{@code ApplicationContextInitializer} processors are encouraged to detect
* whether Spring's {@link org.springframework.core.Ordered Ordered} interface has been
* implemented or if the @{@link org.springframework.core.annotation.Order Order}
* annotation is present and to sort instances accordingly if so prior to invocation.
*
* @author Chris Beams
* @since 3.1
* @see org.springframework.web.context.ContextLoader#customizeContext
* @see org.springframework.web.context.ContextLoader#CONTEXT_INITIALIZER_CLASSES_PARAM
* @see org.springframework.web.servlet.FrameworkServlet#setContextInitializerClasses
* @see org.springframework.web.servlet.FrameworkServlet#applyInitializers
*/
public interface ApplicationContextInitializer<C extends ConfigurableApplicationContext> { /**
* Initialize the given application context.
* @param applicationContext the application to configure
*/
void initialize(C applicationContext); }
1.2、使用步骤
步骤一、写一个类,实现ApplicationContextInitializer接口
步骤二、注册ApplicationContextInitializer接口的实现
注册方式
方式一、SpringApplication
SpringApplication application = new SpringApplication(App.class);
application.addInitializers(new MyApplicationContextInitializer());
方式二、配置文件
context.initializer.classes=com.lhx.spring.springboot_enableauto.MyApplicationContextInitializer
多个用逗号隔开
方式三、使用spring.factories配置机制,注册监听器
在需要注入的项目包中添加META-INF/spring.factories
org.springframework.context.ApplicationContextInitializer=类名
1.3、使用:
新建一个:MyApplicationContextInitializer
package com.lhx.spring.springboot_enableauto; import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext; public class MyApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> { @Override
public void initialize(ConfigurableApplicationContext applicationContext) {
System.out.println("bean count:" + applicationContext.getBeanDefinitionCount());
// ConfigurableListableBeanFactory factory =
// applicationContext.getBeanFactory();
} }
调用
package com.lhx.spring.springboot_enableauto; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext; @SpringBootApplication
public class App {
public static void main(String[] args) {
// ConfigurableApplicationContext context = SpringApplication.run(App.class,
// args);
SpringApplication application = new SpringApplication(App.class);
application.addInitializers(new MyApplicationContextInitializer());
ConfigurableApplicationContext context = application.run(args); context.close();
}
}
2、CommandLineRunner、ApplicationRunner【类似开机自启动】
2.1、作用于实现
作用:在spring容器全部初始化完毕,接口在容器启动成功后的最后一步回调
* 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.
实现
/*
* 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; }
2.2、使用步骤
步骤一、写一个类实现CommandLineRunner接口
步骤二、把该类加入到Spring容器之中,可以通过@Order或Ordered接口控制顺序,注解越小越先执行
2.3、使用
新建一个类ServerSuccessReport实现接口CommandLineRunner
package com.lhx.spring.springboot_enableauto; import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component; @Component
public class ServerSuccessReport implements CommandLineRunner { @Override
public void run(String... args) throws Exception {
System.out.println("----CommandLineRunner执行-----");
} }
注意同类接口
ApplicationRunner,
void run(ApplicationArguments args)
只是参数不一样
CommandLineRunner是原始参数,没有任何处理
ApplicationRunner是ApplicationArguments 对象,是对原始参数进一步的封装
3.ApplicationArguments
是对参数(main方法)进一步重载
可以解析--name=value的,可以通过name获取value
package com.lhx.spring.springboot_enableauto; import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext; @SpringBootApplication
public class App {
public static void main(String[] args) {
SpringApplication application = new SpringApplication(App.class);
ConfigurableApplicationContext context = application.run(args); ApplicationArguments arguments = context.getBean(ApplicationArguments.class);
System.out.println(arguments.getSourceArgs().length);
System.out.println(arguments.getOptionNames());
System.out.println(arguments.getOptionValues("name")); context.close();
}
}
010-Spring Boot 扩展分析-ApplicationContextInitializer、CommandLineRunner、ApplicationRunner的更多相关文章
- Spring Boot 扩展点应用之工厂加载机制
Spring 工厂加载机制,即 Spring Factories Loader,核心逻辑是使用 SpringFactoriesLoader 加载由用户实现的类,并配置在约定好的META-INF/spr ...
- Spring Boot 启动载入数据 CommandLineRunner
实际应用中,我们会有在项目服务启动的时候就去载入一些数据或做一些事情这种需求. 为了解决这种问题.Spring Boot 为我们提供了一个方法.通过实现接口 CommandLineRunner 来实现 ...
- spring boot原理分析
1.分析spring-boot-starter-parent <parent> <groupId>org.springframework.boot</groupId> ...
- spring boot原理分析启动依赖中parent帮我们干了什么
主要内容: 1:分析spring-boot-starter-parent 这个依赖 通过前面几篇文章的学习,我们感受到了spring boot的魅力.最明显的感觉就是pom.xml文件.代码少了很多. ...
- spring boot 扩展之AutoConfigurationImportListener
最近阅读spring boot源码时发现,发现当spring使用ConfigurationClassParser加载使用@Configuration注解类后,会使用AutoConfigurationI ...
- Spring Boot 实战与原理分析视频课程
Spring Boot 实战与原理分析视频课程 链接:https://pan.baidu.com/share/init?surl=PeykcoeqZtd1d9lN9V_F-A 提取码: 关注公众号[G ...
- 精尽Spring Boot源码分析 - Condition 接口的扩展
该系列文章是笔者在学习 Spring Boot 过程中总结下来的,里面涉及到相关源码,可能对读者不太友好,请结合我的源码注释 Spring Boot 源码分析 GitHub 地址 进行阅读 Sprin ...
- Spring Boot 启动原理分析
https://yq.aliyun.com/articles/6056 转 在spring boot里,很吸引人的一个特性是可以直接把应用打包成为一个jar/war,然后这个jar/war是可以直接启 ...
- spring boot应用启动原理分析
spring boot quick start 在spring boot里,很吸引人的一个特性是可以直接把应用打包成为一个jar/war,然后这个jar/war是可以直接启动的,不需要另外配置一个We ...
随机推荐
- 权限控制(vue)
权限控制(vue) 经常会遇到,角色权限控制问题,若是页面控制,倒好说,可如果是当前页面部分可见不可见,这就有些麻烦,如果加上条件就更加苛刻.之前只是简单的v-if进行控制,如今想试试指令(网上一直有 ...
- Pygame播放背景音乐与音效
1.播放背景音乐 pygame.mixer.music.load() 加载MP3格式 加入pygame.mixer.init()即可 第十一行第一个参数:播放次数(n>0),n=0时播放1次,- ...
- 您的浏览器没有获得Java Virtual Machine(JVM)支持。可能由于没有安装JVM或者已安装但是没有启用。请安装JVM1.5或者以上版本,如果已安装则启用它。
您的浏览器没有获得Java Virtual Machine(JVM)支持.可能由于没有安装JVM或者已安装但是没有启用.请安装JVM1.5或者以上版本,如果已安装则启用它. https://www.j ...
- C#/Java 调用WSDL接口及方法
一.C#利用vs里面自带的“添加web引用”功能: 1.首先需要清楚WSDL的引用地址 如:http://www.webxml.com.cn/Webservices/WeatherWebServic ...
- JAVA 泛型 - Class<T>
Class 类 Class 已经泛型化了,但是很多人一开始都感觉其泛型化的方式很混乱.Class 中类型参数 T 的含义是什么?事实证明它是所引用的类接口.怎么会是这样的呢?那是一个循环推理?如果不是 ...
- linux下的数据备份工具rsync讲解
linux下的数据备份工具 rsync(remote sync 远程同步) 名词解释: sync(Synchronize,即“同步”)为UNIX操作系统的标准系统调用,功能为将内核文件系统缓冲区的 ...
- linux添加头文件路径
gcc demo.c -o demo -I/tools/libevent/include -L/tools/libevent/lib -levent -I:头文件目录 -L:静态库目录 -l:静态库 ...
- CF1151F Sonya and Informatics (计数dp+矩阵优化)
题目地址 Solution (duyi是我们的红太阳) (这里说一句:这题看上去是一个概率dp,鉴于这题的概率dp写法看上去不好写,我们其实可以写一个计数dp) 首先拿到这个题目我们要能设出一个普通d ...
- Mybatis(三)MyBatis 动态SQL
在 MyBatis 3 之前的版本中,使用动态 SQL 需要学习和了解非常多的标签,现在 MyBatis 采用了功能强大的 OGNL( Object-Graph Navigation Language ...
- 前端之JQuery:JQuery扩展和事件
jQuery之jQuery扩展和事件 一.jQuery事件 常用事件 blur([[data],fn]) 失去焦点 focus([[data],fn]) 获取焦点( 搜索框例子) change([[d ...