ApplicationContextFactory

简介(What)

ApplicationContextFactory是Spring Boot从2.4.0引入的供SpringApplication使用用于创建ConfigurableApplicationContext的策略工厂接口。

定义(Definition)

ApplicationContextFactory接口定义了一个根据Web应用类型(WebApplicationType)创建ConfigurableApplicationContext的方法,其定义如下:

package org.springframework.boot;

@FunctionalInterface
public interface ApplicationContextFactory {

    ConfigurableApplicationContext create(WebApplicationType webApplicationType);

}

功能(Feature)

除了上述的接口方法,ApplicationContextFactory还提供了两个可以直接使用的静态方法和一个默认的实现:

    static ApplicationContextFactory ofContextClass(Class<? extends ConfigurableApplicationContext> contextClass) {
        return of(() -> BeanUtils.instantiateClass(contextClass));
    }
    static ApplicationContextFactory of(Supplier<ConfigurableApplicationContext> supplier) {
        return (webApplicationType) -> supplier.get();
    }
WebApplicationType ConfigurableApplicationContext
SERVLET AnnotationConfigServletWebServerApplicationContext
REACTIVE AnnotationConfigReactiveWebServerApplicationContext
default AnnotationConfigApplicationContext
    ApplicationContextFactory DEFAULT = (webApplicationType) -> {
        try {
            switch (webApplicationType) {
                case SERVLET:
                    return new AnnotationConfigServletWebServerApplicationContext();
                case REACTIVE:
                    return new AnnotationConfigReactiveWebServerApplicationContext();
                default:
                    return new AnnotationConfigApplicationContext();
            }
        } catch (Exception ex) {
            throw new IllegalStateException("Unable create a default ApplicationContext instance, "
                + "you may need a custom ApplicationContextFactory", ex);
        }
    };