【spring-boot】SpringApplication学习——prepareContext()方法详解

写在前面

在SpringApplication的run()方法启动spring应用的过程中,有三个非常重要的方法,与IOC容器的初始化有关,分别是:

  1. createApplicationContext()
  2. prepareContext();
  3. refreshContext();

这里主要记录关于prepareContext()方法有关的学习笔记。

主要的参数列表

参数类型 参数简要说明
ConfigurableApplicationContext context createApplicationContext()方法的返回值,代表应用上下文
ConfigurableEnvironment environment 系统的环境变量信息的接口类
SpringApplicationRunListeners listeners SpringApplicationRunListener的集合类
ApplicationArguments applicationArguments 应用参数
Banner printedBanner 打印的Banner信息

ConfigurableEnvironment

AbstractEnvironment是实现ConfigurableEnvironment的抽象类,StandardEnvironment继承了AbstractEnvironment,因此StandardEnvironment是ConfigurableEnvironment 的一个实现类。在spring的官方文档中有这样一段话:

When an Environment is being used by an ApplicationContext, it is important that any such PropertySource manipulations be performed before the context’s refresh() method is called. This ensures that all property sources are available during the container bootstrap process, including use by property placeholder configurers.

大概意思就是说如果在ApplicationContext中使用到了系统环境变量类Environment(也可以是继承种的下游类或者接口),那么在调用上下文context的refresh()方法之前,那些关于PropertySource的操作应该全部操作完成,这一点非常的重要,因为这样可以确保在整个容器启动的过程中,所有的property sources都是可用的。
关于这一点,在下面ConfigurableEnvironment的实例代码中也得到了验证。

下面的代码示例表示是在环境变量中添加一个新的property sources。

@ComponentScan("com.xlrainy")
@EnableAutoConfiguration
@Configuration
@MapperScan("com.xlrainy.domain")
public class MyApplication {

    public static void main(String[] args){

        SpringApplication application = new SpringApplication(MyApplication.class);

        /**
         * ConfigurableEnvironment示例代码部分
         */
        ConfigurableEnvironment environment = new StandardEnvironment();
        MutablePropertySources propertySources = environment.getPropertySources();
        Map<String, Object> myMap = new HashMap<>();
        myMap.put("xlcheng", "zhangsy");
        propertySources.addFirst(new MapPropertySource("MY_P", myMap));
        System.err.println(propertySources.get("MY_P"));

        application.run(args);
    }
}

在environment中添加了一个名为"MY_P"的属性,name为"xlcheng",value为"zhangsy",在run()方法之前调用,启动spring应用,在终端的输出
【spring-boot】SpringApplication学习——prepareContext()方法详解
可以看到在Banner输出之前对这些Environment 属性进行了配置,也就是在refresh()方法被调用之前完成了环境属性的操作。

未完待续。。。。