Springboot默认加载application.yml原理

Springboot默认加载application.yml原理以及扩展

SpringApplication.run(…)默认会加载classpath下的application.yml或application.properties配置文件。公司要求搭建的框架默认加载一套默认的配置文件demo.properties,让开发人员实现“零”配置开发,但是前提如果开发人员在application.yml或application.properties文件中自定义配置,则会“覆盖”默认的demo.properties文件,按照Springboot外部化配置的特性(优先使用先加载的),只要demo.properties配置在application.yml或application.properties 配置之后加载到environment中即可。

一、SpirngApplication.run(…)源码分析

通过源码分析,得知Springboot加载配置文件,是利用Spring的事件机制,通过EventPublishingRunListener取发布准备资源事件ApplicationEnvironmentPreparedEvent,被ConfigFileApplicationListener监听到,从而来实现资源的加载

具体源码如下:

    public ConfigurableApplicationContext run(String... args) {
   
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        ConfigurableApplicationContext context = null;
        Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
        configureHeadlessProperty();
        //这里是扩展的关键点
        SpringApplicationRunListeners listeners = getRunListeners(args);
        listeners.starting();
        try {
   
            ApplicationArguments applicationArguments = new DefaultApplicationArguments(
                    args);
            //这里是加载资源的关键
            ConfigurableEnvironment environment = prepareEnvironment(listeners,
                    applicationArguments);
            ....
    }
        
//从方法名称来看就是准备environment的即配置信息
   private ConfigurableEnvironment prepareEnvironment(
            SpringApplicationRunListeners listeners,
            ApplicationArguments applicationArguments) {
   
        // Create and configure the environment
        ConfigurableEnvironment environment = getOrCreateEnvironment();
        configureEnvironment(env

你可能感兴趣的:(java后端,springboot)