点击上方"开发者的花花世界",选择"设为星标"技术干货不定时送达!
一、 ApplicationContextInitializer 介绍
首先看下spring官方说明
源码
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* @param <C> the application context type* @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);}
简单说明一下:
•用于spring上下文初始化的回调函数在上下文(ConfigurableApplicationContext)刷新(refresh)之前调用。•通常被用作web应用,在一些程序设计在spring容器初始化使用。比如说注册一些熟悉配置或者激活一些配置文件针对(ConfigurableApplicationContext的getEnvironment()方法)。参考ContextLoader和FrameworkServlet支持定义一个"contextInitializerClasses"上下文参数或者初始化参数。•可排序的(实现Ordered接口,或者添加@Order注解)
二、 ApplicationContextInitializer实现方式
首先新建一个类 MyApplicationContextInitializer 并实现 ApplicationContextInitializer 接口
•SpringBoot的main方法添加
@SpringBootApplicationpublic class Application {public static void main(String[] args) {SpringApplication application = new SpringApplication(Application.class);application.addInitializers(new MyApplicationContextInitializer());application.run(args);}}
•在application.properties中配置
context.initializer.classes=org.springframework.boot.demo.common.MyApplicationContextInitializer
•SpringBoot的SPI扩展---META-INF/spring.factories中配置
org.springframework.context.ApplicationContextInitializer=org.springframework.boot.demo.common.MyApplicationContextInitializer
关注Github:1/2极客[1]
关注博客:御前提笔小书童[2]
关注网站:HuMingfeng[3]
关注公众号:开发者的花花世界
References
[1]
1/2极客: https://github.com/humingfeng[2]
御前提笔小书童: https://blog.csdn.net/qq_22260641[3]
HuMingfeng: https://royalscholar.cn
喜欢就点个"在看"呗^_^
文章转载自开发者的花花世界,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。






