其实他借助了 Spring的两个特性 , 第一个就是org.springframework.core.env.Environment , 这个是Spring所有配置信息的元信息接口, 其中其子实现类 ConfigurableEnvironment , 使我们需要拿到的对象,对其进行修改
还有一个就是BeanPostProcess , Bean初始化完成的后置处理器, 这里面可以拿到已经实例化完成的Bean. 此时我们可以对其进行过滤 以及其他手脚 , 这个借助于Spring的单例对象模式 ,真的很不错
1. 获取Environment
第一种方式 org.springframework.context.ApplicationContextInitializer 接口
需要在META-INF/spring.factories 中写入,他的初始化很早, 在Bean装载之前,所以不能用@Component注入
org.springframework.context.ApplicationContextInitializer=\
com.example.springbootconfig.autoconfig.ConfigAutoApplication
复制代码public class ConfigAutoApplication implements ApplicationContextInitializer{
@Override
public void initialize(ConfigurableApplicationContext applicationContext){
ConfigurableEnvironment environment = applicationContext.getEnvironment();
// 处理
}
}
复制代码第二种方式 org.springframework.boot.env.EnvironmentPostProcessor 接口
需要在 META-INF/spring.factories 中添加
org.springframework.boot.env.EnvironmentPostProcessor=\
com.example.springbootconfig.autoconfig.EnvironmentAutoWire
复制代码
此时可以通过
public class EnvironmentAutoWire implements EnvironmentPostProcessor{
@Override
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application){
// 获取对象
}
}
复制代码第三种方式 : org.springframework.context.EnvironmentAware
@Component
public class ConfigEnvironme