springboot的EnvironmentPostProcessor接口方法源码解析

 更新时间:2023年08月24日 09:45:54   作者:codecraft  
这篇文章主要介绍了springboot的EnvironmentPostProcessor接口方法源码解析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

本文主要研究一下springboot的EnvironmentPostProcessor

EnvironmentPostProcessor

org/springframework/boot/env/EnvironmentPostProcessor.java

@FunctionalInterface
public interface EnvironmentPostProcessor {

    /**
     * Post-process the given {@code environment}.
     * @param environment the environment to post-process
     * @param application the application to which the environment belongs
     */
    void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application);

}

 springboot提供了EnvironmentPostProcessor接口,该接口有postProcessEnvironment方法,其中envrionment参数类型为ConfigurableEnvironment,即应用可以通过实现这个接口进行env环境变量的操作

EnvironmentPostProcessorApplicationListener

org/springframework/boot/env/EnvironmentPostProcessorApplicationListener.java

/**
 * {@link SmartApplicationListener} used to trigger {@link EnvironmentPostProcessor
 * EnvironmentPostProcessors} registered in the {@code spring.factories} file.
 *
 * @author Phillip Webb
 * @since 2.4.0
 */
public class EnvironmentPostProcessorApplicationListener implements SmartApplicationListener, Ordered {
    /**
     * The default order for the processor.
     */
    public static final int DEFAULT_ORDER = Ordered.HIGHEST_PRECEDENCE + 10;
    private final DeferredLogs deferredLogs;
    private int order = DEFAULT_ORDER;
    private final EnvironmentPostProcessorsFactory postProcessorsFactory;
    /**
     * Create a new {@link EnvironmentPostProcessorApplicationListener} with
     * {@link EnvironmentPostProcessor} classes loaded via {@code spring.factories}.
     */
    public EnvironmentPostProcessorApplicationListener() {
        this(EnvironmentPostProcessorsFactory
                .fromSpringFactories(EnvironmentPostProcessorApplicationListener.class.getClassLoader()));
    }
    /**
     * Create a new {@link EnvironmentPostProcessorApplicationListener} with post
     * processors created by the given factory.
     * @param postProcessorsFactory the post processors factory
     */
    public EnvironmentPostProcessorApplicationListener(EnvironmentPostProcessorsFactory postProcessorsFactory) {
        this(postProcessorsFactory, new DeferredLogs());
    }
    EnvironmentPostProcessorApplicationListener(EnvironmentPostProcessorsFactory postProcessorsFactory,
            DeferredLogs deferredLogs) {
        this.postProcessorsFactory = postProcessorsFactory;
        this.deferredLogs = deferredLogs;
    }
    @Override
    public boolean supportsEventType(Class<? extends ApplicationEvent> eventType) {
        return ApplicationEnvironmentPreparedEvent.class.isAssignableFrom(eventType)
                || ApplicationPreparedEvent.class.isAssignableFrom(eventType)
                || ApplicationFailedEvent.class.isAssignableFrom(eventType);
    }
    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof ApplicationEnvironmentPreparedEvent) {
            onApplicationEnvironmentPreparedEvent((ApplicationEnvironmentPreparedEvent) event);
        }
        if (event instanceof ApplicationPreparedEvent) {
            onApplicationPreparedEvent((ApplicationPreparedEvent) event);
        }
        if (event instanceof ApplicationFailedEvent) {
            onApplicationFailedEvent((ApplicationFailedEvent) event);
        }
    }
    private void onApplicationEnvironmentPreparedEvent(ApplicationEnvironmentPreparedEvent event) {
        ConfigurableEnvironment environment = event.getEnvironment();
        SpringApplication application = event.getSpringApplication();
        for (EnvironmentPostProcessor postProcessor : getEnvironmentPostProcessors(event.getBootstrapContext())) {
            postProcessor.postProcessEnvironment(environment, application);
        }
    }
    private void onApplicationPreparedEvent(ApplicationPreparedEvent event) {
        finish();
    }
    private void onApplicationFailedEvent(ApplicationFailedEvent event) {
        finish();
    }
    private void finish() {
        this.deferredLogs.switchOverAll();
    }
    List<EnvironmentPostProcessor> getEnvironmentPostProcessors(ConfigurableBootstrapContext bootstrapContext) {
        return this.postProcessorsFactory.getEnvironmentPostProcessors(this.deferredLogs, bootstrapContext);
    }
    @Override
    public int getOrder() {
        return this.order;
    }
    public void setOrder(int order) {
        this.order = order;
    }
}

EnvironmentPostProcessorApplicationListener用于在接收到ApplicationEnvironmentPreparedEvent事件时触发执行EnvironmentPostProcessor的postProcessEnvironment方法

# Application Listeners
org.springframework.context.ApplicationListener=\
org.springframework.boot.ClearCachesApplicationListener,\
org.springframework.boot.builder.ParentContextCloserApplicationListener,\
org.springframework.boot.context.FileEncodingApplicationListener,\
org.springframework.boot.context.config.AnsiOutputApplicationListener,\
org.springframework.boot.context.config.DelegatingApplicationListener,\
org.springframework.boot.context.logging.LoggingApplicationListener,\
org.springframework.boot.env.EnvironmentPostProcessorApplicationListener,\
org.springframework.boot.liquibase.LiquibaseServiceLocatorApplicationListener

示例

public class EnvironmentPostProcessorExample implements EnvironmentPostProcessor {
    private final YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        Resource path = new ClassPathResource("com/example/myapp/config.yml");
        PropertySource<?> propertySource = loadYaml(path);
        environment.getPropertySources().addLast(propertySource);
    }
    private PropertySource<?> loadYaml(Resource path) {
        if (!path.exists()) {
            throw new IllegalArgumentException("Resource " + path + " does not exist");
        }
        try {
            return this.loader.load("custom-resource", path).get(0);
        }
        catch (IOException ex) {
            throw new IllegalStateException("Failed to load yaml configuration from " + path, ex);
        }
    }
}

 EnvironmentPostProcessorExample实现了postProcessEnvironment方法,它额外加载com/example/myapp/config.yml里头的配置最为最后的propertySource

小结

springboot的EnvironmentPostProcessor提供了一个environment的扩展接口,方便应用去做environment的扩展,比如扩展propertySource等

以上就是springboot的EnvironmentPostProcessor接口方法源码解析的详细内容,更多关于springboot EnvironmentPostProcessor的资料请关注脚本之家其它相关文章!

相关文章

  • maven的pom文件与打包详解

    maven的pom文件与打包详解

    pom文件定于了一个maven项目的maven配置,一般pom文件的放在项目或者模块的根目录下。本文详细的介绍了pom文件配置,感兴趣的可以了解一下
    2021-08-08
  • Java中Arrays.asList()需要注意的坑

    Java中Arrays.asList()需要注意的坑

    在Java中,我们经常需要将数组转换为List来方便地进行操作,Arrays.asList()方法是一种常见的方式,本文主要介绍了Java中Arrays.asList()需要注意的坑,具有一定的参考价值,感兴趣的可以了解一下
    2023-08-08
  • springboot yml配置文件定义list集合、数组和map以及使用中的错误

    springboot yml配置文件定义list集合、数组和map以及使用中的错误

    这篇文章主要介绍了springboot yml配置文件定义list集合、数组和map以及使用中遇到的错误问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-07-07
  • 新手初学Java常见排序算法

    新手初学Java常见排序算法

    排序(Sorting) 是计算机程序设计中的一种重要操作,它的功能是将一个数据元素(或记录)的任意序列,重新排列成一个关键字有序的序列
    2021-07-07
  • 新手了解java基础知识(一)

    新手了解java基础知识(一)

    这篇文章主要介绍了Java基础知识,本文介绍了Java语言相关的基础知识、历史介绍、主要应用方向等内容,需要的朋友可以参考下,希望对你有所帮助
    2021-07-07
  • 分布式框架Zookeeper api的使用介绍

    分布式框架Zookeeper api的使用介绍

    Zookeeper作为⼀个分布式框架,主要用来解决分布式⼀致性问题,它提供了简单的分布式原语,并且对多种编程语⾔提供了API,所以接下来重点来看下Zookeeper的java客户端API使用方式
    2022-09-09
  • request.getParameter()方法的简单理解与运用方式

    request.getParameter()方法的简单理解与运用方式

    在JavaWeb开发中,request对象扮演着至关重要的角色,它是HTTP请求的封装,request.getParameter()用于获取客户端通过GET或POST方式发送的参数,与之相对,request.setAttribute()用于在服务器端设置属性,这些属性只在一次请求中有效
    2024-10-10
  • Mybatis-Plus自动生成的数据库id过长的解决

    Mybatis-Plus自动生成的数据库id过长的解决

    这篇文章主要介绍了Mybatis-Plus自动生成的数据库id过长的解决,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-12-12
  • SpringMVC数据响应详细介绍

    SpringMVC数据响应详细介绍

    Spring MVC 是 Spring 提供的一个基于 MVC 设计模式的轻量级 Web 开发框架,本质上相当于 Servlet,Spring MVC 角色划分清晰,分工明细,本章来讲解SpringMVC数据响应
    2023-02-02
  • Maven通过filtering标签读取变量配置的三种方法

    Maven通过filtering标签读取变量配置的三种方法

    在日常开发中,我们大多都会有开发环境、测试环境、生产环境等,不同环境的参数肯定不一样,本文主要介绍了Maven通过filtering标签读取变量配置的三种方法,感兴趣的可以了解一下
    2024-03-03

最新评论