动态管理配置文件扩展接口EnvironmentPostProcessor

前言

SpringBoot 支持动态的读取配置文件,留下了一个扩展接口 org.springframework.boot.env.EnvironmentPostProcessor,使用这个进行配置文件的集中管理,而不需要每个项目都去配置配置文件。这种方法也是springboot框架留下的一个扩展(可以自己去扩展)。

使用方式

首先,我们建立一个类 MyEnvironmentPostProcessor

package com.example.demo.loader;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.stereotype.Component;

/**
 * @author :admin Created in 2019/4/3
 */
@Component
public class MyEnvironmentPostProcessor implements EnvironmentPostProcessor {

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment configurableEnvironment,
            SpringApplication springApplication) {
        try {
            InputStream inputStream = new FileInputStream("/Users/admin/temp/my.properties");
            Properties properties = new Properties();
            properties.load(inputStream);
            PropertiesPropertySource propertySource = new PropertiesPropertySource("my", properties);
            configurableEnvironment.getPropertySources().addLast(propertySource);
        } catch (Exception e) {

        }
    }
}

然后,在META-INF下创建spring.factories

org.springframework.boot.env.EnvironmentPostProcessor=com.example.demo.loader.MyEnvironmentPostProcessor

其次,建立配置文件my.properties

name=root

最后,测试

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(DemoApplication.class, args);
        String root = context.getEnvironment().getProperty("name");
        System.out.println(root);
    }

}

EnvironmentPostProcessor 介绍

  • 在spring上下文构建之前可以设置一些系统配置。
  • EnvironmentPostProcessor的实现类必须要在META-INF/spring.factories文件中去注册,并且注册的是全类名。
  • 鼓励EnvironmentPostProcessor处理器检测Org.springframework.core.Ordered注解,这样相应的实例也会按照@Order注解的顺序去被调用。

参考文章

Spring Boot启动流程详解:http://zhaox.github.io/java/2016/03/22/spring-boot-start-flow

你可能感兴趣的:(动态管理配置文件扩展接口EnvironmentPostProcessor)