Spring - ApplicationContextInitializer 扩展接口

Posted 小小工匠

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring - ApplicationContextInitializer 扩展接口相关的知识,希望对你有一定的参考价值。

文章目录


Pre

Spring Boot - 扩展接口一览

org.springframework.context.ApplicationContextInitializer扩展点


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
 */
@FunctionalInterface
public interface ApplicationContextInitializer<C extends ConfigurableApplicationContext> 

	/**
	 * Initialize the given application context.
	 * @param applicationContext the application to configure
	 */
	void initialize(C applicationContext);



Callback interface for initializing a Spring ConfigurableApplicationContext prior to being refreshed.

该接口是整个spring容器在刷新之前初始化ConfigurableApplicationContext的回调接口,即在容器刷新之前会调用该类的initialize方法。

实现这个接口可以在整个spring容器还没被初始化之前搞事情。

举几个可能的例子:

  • 利用这时候class还没被类加载器加载的时机,进行动态字节码注入
  • 应用配置激活

扩展接口

package com.artisan.bootspringextend.testextends;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;

/**
 * @author 小工匠
 * @version 1.0
 * @date 2022/11/26 22:16
 * @mark: show me the code , change the world
 */
@Slf4j
public class ExtendApplicationContextInitializer implements ApplicationContextInitializer 
    @Override
    public void initialize(ConfigurableApplicationContext applicationContext) 
        log.info("ExtendApplicationContextInitializer # initialize  Called");
    

    

扩展生效方式

方式一 : Spring SPI扩展

在spring.factories中加入

org.springframework.context.ApplicationContextInitializer=com.artisan.bootspringextend.testextends.ExtendApplicationContextInitializer

方式二 : 配置文件

context.initializer.classes=com.artisan.bootspringextend.testextends.ExtendApplicationContextInitializer

方式三 :启动类手工add

调整一下启动方式

   SpringApplication springApplication = new SpringApplication(BootSpringExtendApplication.class);
   springApplication.addInitializers(new ExtendApplicationContextInitializer());

  springApplication.run(args);

测试结果

  .   ____          _            __ _ _
 /\\\\ / ___'_ __ _ _(_)_ __  __ _ \\ \\ \\ \\
( ( )\\___ | '_ | '_| | '_ \\/ _` | \\ \\ \\ \\
 \\\\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v2.4.2)

2022-11-26 22:38:12.280  INFO 15048 --- [           main] .b.t.ExtendApplicationContextInitializer : ExtendApplicationContextInitializer # initialize  Called
2022-11-26 22:38:12.305  INFO 15048 --- [           main] c.a.b.BootSpringExtendApplication        : Starting BootSpringExtendApplication using Java 1.8.0_261 on LAPTOP-JF3RBRRJ with PID 15048 (D:\\IdeaProjects\\boot2\\boot-spring-extend\\target\\classes started by artisan in D:\\IdeaProjects\\boot2)
2022-11-26 22:38:12.306  INFO 15048 --- [           main] c.a.b.BootSpringExtendApplication        : No active profile set, falling back to default profiles: default
2022-11-26 22:38:12.723  INFO 15048 --- [           main] c.a.b.BootSpringExtendApplication        : Started BootSpringExtendApplication in 0.777 seconds (JVM running for 1.916)

Process finished with exit code 0

2022-11-26 22:38:12.280  INFO 15048 --- [           main] .b.t.ExtendApplicationContextInitializer : ExtendApplicationContextInitializer # initialize  Called

以上是关于Spring - ApplicationContextInitializer 扩展接口的主要内容,如果未能解决你的问题,请参考以下文章

Spring + Hibernate + JPA [关闭]

Spring Web 项目Junit测试报错问题

Spring 类构造器初始化实例

ContextLoader和ContextLoaderListener

ContextLoader和ContextLoaderListener

面试阿里,字节,美团必看的Spring的Bean管理详解