1.介绍

用于Spring容器ConfigurableApplicationContext在刷新之前初始化Spring的回调接口。

通常在需要对应用程序上下文进行一些编程初始化的Web应用程序中使用。例如,注册属性源或针对上下文环境激活配置文件。

ApplicationContextInitializer鼓励处理器检测Spring的Ordered 接口是否已实现或@Order注释是否存在,并在调用之前对实例进行相应的排序。

public interface ApplicationContextInitializer<C extends ConfigurableApplicationContext> {
/**
* 初始化给定的应用程序上下文.
*/
void initialize(C applicationContext);
}

2.使用

//指定顺序,Order值越小优先级越高
@Order(100)
public class CustomApplicationContextInitializer implements ApplicationContextInitializer {
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
// 打印容器里面有多少个bean
System.out.println("bean count=====" + applicationContext.getBeanDefinitionCount());
// 打印所有 beanName
System.out.println(applicationContext.getBeanDefinitionCount() + "个Bean的名字如下:");
String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();
for (String beanName : beanDefinitionNames) {
System.out.println("--------"+beanName);
}
}
}

实现方式一: SPI扩展-配置文件中配置

在项目下的resources下新建META-INF文件夹,文件夹下新建spring.factories文件

org.springframework.context.ApplicationContextInitializer=com.yue.sso.CustomApplicationContextInitializer

实现方式二:main函数中添加

@SpringBootApplication
@ComponentScan(basePackages = "com.yue")
public class SsoApplication {
public static void main(String[] args) {
SpringApplication application = new SpringApplication(SsoApplication.class);
application.addInitializers(new CustomApplicationContextInitializer());
application.run(args);
}
}

3.触发位置

public ConfigurableApplicationContext run(String... args) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = null;
Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
configureHeadlessProperty();
SpringApplicationRunListeners listeners = getRunListeners(args);
listeners.starting();
try {
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
configureIgnoreBeanInfo(environment);
Banner printedBanner = printBanner(environment);
context = createApplicationContext();
exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
new Class[] { ConfigurableApplicationContext.class }, context);
     // 准备容器:初始化在此完成
prepareContext(context, environment, listeners, applicationArguments, printedBanner);
refreshContext(context);
afterRefresh(context, applicationArguments);
stopWatch.stop();
if (this.logStartupInfo) {
new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
}
listeners.started(context);
callRunners(context, applicationArguments);
}
catch (Throwable ex) {
handleRunFailure(context, ex, exceptionReporters, listeners);
throw new IllegalStateException(ex);
}
try {
listeners.running(context);
}
catch (Throwable ex) {
handleRunFailure(context, ex, exceptionReporters, null);
throw new IllegalStateException(ex);
}
return context;
}
private void prepareContext(ConfigurableApplicationContext context, ConfigurableEnvironment environment,
SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments, Banner printedBanner) {
context.setEnvironment(environment);
postProcessApplicationContext(context);
// 执行所有ApplicationContextInitializer实现类初始化
applyInitializers(context);
listeners.contextPrepared(context);
if (this.logStartupInfo) {
logStartupInfo(context.getParent() == null);
logStartupProfileInfo(context);
}
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
beanFactory.registerSingleton("springApplicationArguments", applicationArguments);
if (printedBanner != null) {
beanFactory.registerSingleton("springBootBanner", printedBanner);
}
if (beanFactory instanceof DefaultListableBeanFactory) {
((DefaultListableBeanFactory) beanFactory)
.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
}
if (this.lazyInitialization) {
context.addBeanFactoryPostProcessor(new LazyInitializationBeanFactoryPostProcessor());
}
Set<Object> sources = getAllSources();
Assert.notEmpty(sources, "Sources must not be empty");
load(context, sources.toArray(new Object[0]));
listeners.contextLoaded(context);
}

Spring扩展之一:ApplicationContextInitializer的更多相关文章

  1. spring扩展点之三:Spring 的监听事件 ApplicationListener 和 ApplicationEvent 用法,在spring启动后做些事情

    <spring扩展点之三:Spring 的监听事件 ApplicationListener 和 ApplicationEvent 用法,在spring启动后做些事情> <服务网关zu ...

  2. spring扩展点之二:spring中关于bean初始化、销毁等使用汇总,ApplicationContextAware将ApplicationContext注入

    <spring扩展点之二:spring中关于bean初始化.销毁等使用汇总,ApplicationContextAware将ApplicationContext注入> <spring ...

  3. spring扩展点整理

    本文转载自spring扩展点整理 背景 Spring的强大和灵活性不用再强调了.而灵活性就是通过一系列的扩展点来实现的,这些扩展点给应用程序提供了参与Spring容器创建的过程,好多定制化的东西都需要 ...

  4. spring扩展点之五:ApplicationContextInitializer实现与使用

    ApplicationContextInitializer是Spring框架原有的东西,这个类的主要作用就是在ConfigurableApplicationContext类型(或者子类型)的Appli ...

  5. spring扩展点之一:BeanFactoryPostProcessor和BeanPostProcessor

    一.BeanFactoryPostProcessor和BeanPostProcessor的区别 BeanFactoryPostProcessor和BeanPostProcessor都是spring初始 ...

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

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

  7. Spring扩展:替换IOC容器中的Bean组件 -- @Replace注解

    1.背景:     工作中是否有这样的场景?一个软件系统会同时有多个不同版本部署,比如我现在做的IM系统,同时又作为公司的技术输出给其他银行,不同的银行有自己的业务实现(比如登陆验证.用户信息查询等) ...

  8. spring扩展的常用接口

    一:ApplicationContextAware接口 实现ApplicationContextAware接口,重写setApplicationContext方法,可以将spring容器上下文对象注入 ...

  9. Spring扩展:Spring的IoC容器(注入对象的方式和编码方式)

    二.Spring的IoC容器 IoC:Inversion of Control(控制反转) DI:Dependency Injection(依赖注入) 三.依赖注入的方式 (1)构造注入 (2)set ...

随机推荐

  1. phpstorm配置sftp自动上传

    勾选自动上传 手动上传   qq_23049573 原创文章 14获赞 4访问量 2万+ 关注 私信

  2. django—视图相关

    FBV与CBV FBV:function based view   基于函数的视图 CBV:class based view  基于类的视图 CBV的定义: from django.views imp ...

  3. 通过express快速搭建一个node服务

    Node.js 是一个基于Chrome JavaScript 运行时建立的一个平台.可以理解为是运行在服务端的 JavaScript.如果你是一个前端程序员,不太擅长像PHP.Python或Ruby等 ...

  4. RAM ROM区别记忆

    我老是忘这个 1.概念 RAM即随机存储内存,这种存储器在断电时将丢失其存储内容,故主要用于存储短时间使用的程序.ROM即只读内存,是一种只能读出事先所存数据的固态半导体存储器. 2.对比 手机中的R ...

  5. 【应用服务 App Service】App Service中上传文件/图片(> 2M)后就出现500错误(Maximum request length exceeded).

    问题描述 在使用App Service (Windows)做文件/图片上传时候,时常遇见上传大文件时候出现错误,这是因为IIS对文件的大小由默认限制.当遇见(Maximum request lengt ...

  6. Educational Codeforces Round 95 (Rated for Div. 2)

    CF的Educational Round (Div.2),质量还是蛮高的. A: 水题 #include<cstdio> #include<algorithm> typedef ...

  7. python 作业 日报模板输出

    1 #!/usr/bin/env python 2 # coding: utf-8 3 4 import numpy as np 5 import pandas as pd 6 7 path='C:/ ...

  8. css3滚动条样式美化

    关于滚动条的设计,需要用到css3的微元素,都列在下边吧(以Chrome内核webkit为例). -webkit-scrollbar     滚动条的整体轮廓,width表示纵向滚动条的宽度,heig ...

  9. 虚拟化下Centos7 扩容根分区

    查看分区大小和挂载情况 用到的命令df.lsblk [root@localhost ~]# df -h Filesystem Size Used Avail Use% Mounted on /dev/ ...

  10. 机器学习 第4篇:sklearn 最邻近算法概述

    sklearn.neighbors 提供了针对无监督和受监督的基于邻居的学习方法的功能.监督的基于最邻近的机器学习算法是值:对带标签的数据的分类和对连续数据的预测(回归). 无监督的最近算法是许多其他 ...