springboot系列24,SpringBoot的外部化配置(下)

扩展外部化配置

要做到扩展外部化配置,我们通过之前分析可以知道,environment是放在上下文中使用的,那么肯定要在上下文初始化之前,因为上下文初始化以后,后面其他工具的初始化可能会用到environment,那在那个时候再初始化就没有意义了。

首先是springboot,我们知道springboot的入口是run,进去看源码:

通过之前的分析我们知道,上下文开始初始化是在refreshContext的时候,environment创建是在prepareEnvironment,所以springboot中,尽量在其中间进行初始化。

对于SpringFramework,通过之前我们知道,environment Bean是在prepareBeanFactory方法中创建的,

所以对于SpringFramework,需要在prepareBeanFactory方法之前进行创建。

基于SpringApplicationRunListener#environmentPrepared扩展

首先找一下这个的配置在哪:

所以我们也做同样的配置

/**
 * 扩展{@link PropertySources} {@link SpringApplicationRunListener} 实现
 */
public class ExtendPropertySourceRunListener implements SpringApplicationRunListener , Order {

    private final SpringApplication application;

    private final String[] args;

    public ExtendPropertySourceRunListener(SpringApplication application, String[] args) {
        this.application = application;
        this.args = args;
    }

    @Override
    public void starting() {

    }

    @Override
    public void environmentPrepared(ConfigurableEnvironment environment) {
        MutablePropertySources propertySources = environment.getPropertySources();
        Map<String, Object> source = new HashMap<>();
        source.put("haozi.id" , "6");
        MapPropertySource propertySource = new MapPropertySource("from-environmentPrepared" , source);
        propertySources.addFirst(propertySource);
    }

    @Override
    public void contextPrepared(ConfigurableApplicationContext context) {

    }

    @Override
    public void contextLoaded(ConfigurableApplicationContext context) {

    }

    @Override
    public void started(ConfigurableApplicationContext context) {

    }

    @Override
    public void running(ConfigurableApplicationContext context) {

    }

    @Override
    public void failed(ConfigurableApplicationContext context, Throwable exception) {

    }

    @Override
    public int value() {
        //顺序设置为EventPublishingRunListener后面
        return new EventPublishingRunListener(application , args).getOrder() + 1;
    }

    @Override
    public Class<? extends Annotation> annotationT
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值