SpringBoot 启动流程源码解析

51 阅读3分钟

启动类

@SpringBootApplication
@Slf4j
public class PracticeApplication {
    
    public static void main(String[] args) {
        SpringApplication.run(PracticeApplication.class, args);
    }
}

参数 String[] args

将项目打成jar包之后可以用来传递参数,例如启动的时候

java -jar xxx.jar --server.port=8081 --key=value

@SpringBootApplication
@Slf4j
public class PracticeApplication {
    
    System.out.println("--------------------------");
    for (String e : args) {
        System.out.println("args: " + e);
    }
    System.out.println("--------------------------");
    
    public static void main(String[] args) {
        SpringApplication.run(PracticeApplication.class, args);
    }
}

实例化SpringApplicaiton()

public class SpringApplication {
    
    //..... 省略了很多的方法和属性
    
    private ResourceLoader resourceLoader; // 资源加载器顶级接口;DefaultResourceLoader:资源加载器默认实现类,主要是加载classpath: 路径下的资源
    
    private Set<Class<?>> primarySources; // 存放启动类 和其他类
    
    private WebApplicationType webApplicationType; // 存放应用类型
    
    private Class<?> mainApplicationClass; // 存储启动类
    
    private List<ApplicationContextInitializer<?>> initializers; // 存储ApplicationContextInitializer接口实现类的实例化对象
    
    private List<ApplicationListener<?>> listeners; // 存储ApplicationListener接口实现类的实例化对象
    
    public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) {
        return run(new Class<?>[] { primarySource }, args);
    }
    
    public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
        return new SpringApplication(primarySources).run(args);
    }
    
    public SpringApplication(Class<?>... primarySources) {
        this(null, primarySources);
    }
    
    /**
     * Create a new {@link SpringApplication} instance. The application context will load
     * beans from the specified primary sources (see {@link SpringApplication class-level}
     * documentation for details. The instance can be customized before calling
     * {@link #run(String...)}.
     * @param resourceLoader the resource loader to use
     * @param primarySources the primary bean sources
     * @see #run(Class, String[])
     * @see #setSources(Set)
     */
    public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
        this.resourceLoader = resourceLoader; // 在此处参数为null
        Assert.notNull(primarySources, "PrimarySources must not be null");
         // 记录启动类,在后面使用
        this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
        // 推断web应用类型
        this.webApplicationType = WebApplicationType.deduceFromClasspath(); 
        // 加载配置在spring.factories文件中的ApplicationContextInitializer对应的类型并实例化
        // 并将加载的数据存储在了 initializers 成员变量中。
        setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
        // 初始化监听器 并将加载的监听器实例对象存储在了listeners成员变量中
        setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
        // 反推main方法所在的Class对象 并记录在了mainApplicationClass对象中
        this.mainApplicationClass = deduceMainApplicationClass();
    }
    
    //..... 省略了很多的方法
}

推断应用类型

/**
 * An enumeration of possible types of web application.
 *
 * @author Andy Wilkinson
 * @author Brian Clozel
 * @since 2.0.0
 */
public enum WebApplicationType {

	/**
	 * The application should not run as a web application and should not start an
	 * embedded web server.
	 */
	NONE,

	/**
	 * The application should run as a servlet-based web application and should start an
	 * embedded servlet web server.
	 */
	SERVLET,

	/**
	 * The application should run as a reactive web application and should start an
	 * embedded reactive web server.
	 */
	REACTIVE;

	private static final String[] SERVLET_INDICATOR_CLASSES = { "javax.servlet.Servlet",
			"org.springframework.web.context.ConfigurableWebApplicationContext" };

	private static final String WEBMVC_INDICATOR_CLASS = "org.springframework.web.servlet.DispatcherServlet";

	private static final String WEBFLUX_INDICATOR_CLASS = "org.springframework.web.reactive.DispatcherHandler";

	private static final String JERSEY_INDICATOR_CLASS = "org.glassfish.jersey.servlet.ServletContainer";

	private static final String SERVLET_APPLICATION_CONTEXT_CLASS = "org.springframework.web.context.WebApplicationContext";

	private static final String REACTIVE_APPLICATION_CONTEXT_CLASS = "org.springframework.boot.web.reactive.context.ReactiveWebApplicationContext";
    
    // 利用反射机制查找相应的类
	static WebApplicationType deduceFromClasspath() {
		if (ClassUtils.isPresent(WEBFLUX_INDICATOR_CLASS, null) && !ClassUtils.isPresent(WEBMVC_INDICATOR_CLASS, null)
				&& !ClassUtils.isPresent(JERSEY_INDICATOR_CLASS, null)) {
			return WebApplicationType.REACTIVE;
		}
		for (String className : SERVLET_INDICATOR_CLASSES) {
			if (!ClassUtils.isPresent(className, null)) {
				return WebApplicationType.NONE;
			}
		}
		return WebApplicationType.SERVLET;
	}
}

实例化ApplicationContextInitializerApplicationListener接口的实现类

  1. 找到所有依赖包/META-INF/spring.factories文件中配置的ApplicationContextInitializerApplicationListener接口的实现类
  2. 实例化存储到initializers 和 listeners 属性中
private <T> Collection<T> getSpringFactoriesInstances(Class<T> type) {
    return getSpringFactoriesInstances(type, new Class<?>[] {});
}

private <T> Collection<T> getSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, Object... args) {
    ClassLoader classLoader = getClassLoader();
    // Use names and ensure unique to protect against duplicates
    // 查找spring.factories文件中type接口的实现类
    Set<String> names = new LinkedHashSet<>(SpringFactoriesLoader.loadFactoryNames(type, classLoader));
    // 利用反射机制实例化对象
    List<T> instances = createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names);
    // 依据实现类getOrder()方法中return的值从小到大排序,getOrder()方法为实现Order接口时需要重写的一个方法
    AnnotationAwareOrderComparator.sort(instances);
    return instances;
}

// 查找spring.factories文件中type接口的实现类
public static List<String> loadFactoryNames(Class<?> factoryType, @Nullable ClassLoader classLoader) {
    String factoryTypeName = factoryType.getName();
    return loadSpringFactories(classLoader).getOrDefault(factoryTypeName, Collections.emptyList());
}

private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) {
    MultiValueMap<String, String> result = cache.get(classLoader);
    if (result != null) {
        return result;
    }

    try {
        Enumeration<URL> urls = (classLoader != null ?
                                 classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :
                                 ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));
        result = new LinkedMultiValueMap<>();
        while (urls.hasMoreElements()) {
            URL url = urls.nextElement();
            UrlResource resource = new UrlResource(url);
            Properties properties = PropertiesLoaderUtils.loadProperties(resource);
            for (Map.Entry<?, ?> entry : properties.entrySet()) {
                String factoryTypeName = ((String) entry.getKey()).trim();
                for (String factoryImplementationName : StringUtils.commaDelimitedListToStringArray((String) entry.getValue())) {
                    result.add(factoryTypeName, factoryImplementationName.trim());
                }
            }
        }
        cache.put(classLoader, result);
        return result;
    }
    catch (IOException ex) {
        throw new IllegalArgumentException("Unable to load factories from location [" +
                                           FACTORIES_RESOURCE_LOCATION + "]", ex);
    }
}
// 利用反射实例化对象
private <T> List<T> createSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes,
			ClassLoader classLoader, Object[] args, Set<String> names) {
		List<T> instances = new ArrayList<>(names.size());
		for (String name : names) {
			try {
				Class<?> instanceClass = ClassUtils.forName(name, classLoader);
				Assert.isAssignable(type, instanceClass);
				Constructor<?> constructor = instanceClass.getDeclaredConstructor(parameterTypes);
				T instance = (T) BeanUtils.instantiateClass(constructor, args);
				instances.add(instance);
			}
			catch (Throwable ex) {
				throw new IllegalArgumentException("Cannot instantiate " + type + " : " + name, ex);
			}
		}
		return instances;
}

// 依据实现类getOrder()方法中return的值从小到大排序
// 重写list的比较方法
@Override
public int compare(@Nullable Object o1, @Nullable Object o2) {
    return doCompare(o1, o2, null);
}

private int doCompare(@Nullable Object o1, @Nullable Object o2, @Nullable OrderSourceProvider sourceProvider) {
    boolean p1 = (o1 instanceof PriorityOrdered);
    boolean p2 = (o2 instanceof PriorityOrdered);
    if (p1 && !p2) {
        return -1;
    }
    else if (p2 && !p1) {
        return 1;
    }

    int i1 = getOrder(o1, sourceProvider);
    int i2 = getOrder(o2, sourceProvider);
    return Integer.compare(i1, i2);
}

反推main方法所在的Class对象

在StackTraceElement中找到main方法所在的类,也就是启动类

private Class<?> deduceMainApplicationClass() {
    try {
        StackTraceElement[] stackTrace = new RuntimeException().getStackTrace();
        for (StackTraceElement stackTraceElement : stackTrace) {
            if ("main".equals(stackTraceElement.getMethodName())) {
                return Class.forName(stackTraceElement.getClassName());
            }
        }
    }
    catch (ClassNotFoundException ex) {
        // Swallow and continue
    }
    return null;
}

SpringApplication().run()

调用SpringApplication()对象的run(String... args)方法

/**
 * Run the Spring application, creating and refreshing a new
 * {@link ApplicationContext}.
 * @param args the application arguments (usually passed from a Java main method)
 * @return a running {@link ApplicationContext}
 */
public ConfigurableApplicationContext run(String... args) {
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    ConfigurableApplicationContext context = null;
    Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
    // 配置java.awt.headless属性为true,在服务器上没有检测到显示器时也允许启动
    configureHeadlessProperty();
    // 用到了前面实例化SpringApplication时使用到的方法getSpringFactoriesInstances();
    // 实例化了SpringApplicationRunListener的实现类存放到SpringApplicationRunListeners对象中
    SpringApplicationRunListeners listeners = getRunListeners(args);
    // 调用上面所有已经实例化过的SpringApplicationRunListener的实现类的starting()方法
    listeners.starting();
    try {
        // 将启动类中接收到的参数转化为java对象
        ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
        ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
        configureIgnoreBeanInfo(environment);
        Banner printedBanner = printBanner(environment);
        context = createApplicationContext();
        exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
                                                         new Class[] { ConfigurableApplicationContext.class }, context);
        prepareContext(context, environment, listeners, applicationArguments, printedBanner); // 使用primarySources
        refreshContext(context);
        afterRefresh(context, applicationArguments);
        stopWatch.stop();
        if (this.logStartupInfo) {
            new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
        }
        listeners.started(context);
        callRunners(context, applicationArguments);
    }
    catch (Throwable ex) {
        handleRunFailure(context, ex, exceptionReporters, listeners);
        throw new IllegalStateException(ex);
    }

    try {
        listeners.running(context);
    }
    catch (Throwable ex) {
        handleRunFailure(context, ex, exceptionReporters, null);
        throw new IllegalStateException(ex);
    }
    return context;
}



// 准备环境对象
private ConfigurableEnvironment prepareEnvironment(SpringApplicationRunListeners listeners,
			ApplicationArguments applicationArguments) {
    // Create and configure the environment
    // 根据不同的应用类型(前面已经存储起来的属性webApplicationType)生成不同的环境对象的子类
    ConfigurableEnvironment environment = getOrCreateEnvironment();
    configureEnvironment(environment, applicationArguments.getSourceArgs());
    ConfigurationPropertySources.attach(environment);
    listeners.environmentPrepared(environment);
    bindToSpringApplication(environment);
    if (!this.isCustomEnvironment) {
        environment = new EnvironmentConverter(getClassLoader()).convertEnvironmentIfNecessary(environment,
                                                                                               deduceEnvironmentClass());
    }
    ConfigurationPropertySources.attach(environment);
    return environment;
}

private ConfigurableEnvironment getOrCreateEnvironment() {
    if (this.environment != null) {
        return this.environment;
    }
    switch (this.webApplicationType) {
        case SERVLET:
            return new StandardServletEnvironment();
        case REACTIVE:
            return new StandardReactiveWebEnvironment();
        default:
            return new StandardEnvironment();
    }
}

configureHeadlessProperty()

private static final String SYSTEM_PROPERTY_JAVA_AWT_HEADLESS = "java.awt.headless";

// 配置java.awt.headless属性为true,在服务器上没有检测到显示器时也允许启动
private void configureHeadlessProperty() {
    System.setProperty(SYSTEM_PROPERTY_JAVA_AWT_HEADLESS,
                       System.getProperty(SYSTEM_PROPERTY_JAVA_AWT_HEADLESS, Boolean.toString(this.headless)));
}

getRunListeners()

// 用到了前面实例化SpringApplication时使用到的方法getSpringFactoriesInstances();
private SpringApplicationRunListeners getRunListeners(String[] args) {
    Class<?>[] types = new Class<?>[] { SpringApplication.class, String[].class };
    return new SpringApplicationRunListeners(logger,
                                             getSpringFactoriesInstances(SpringApplicationRunListener.class, types, this, args));
}

class SpringApplicationRunListeners {

	private final Log log;

	private final List<SpringApplicationRunListener> listeners;
    
    // 构造方法
    SpringApplicationRunListeners(Log log, Collection<? extends SpringApplicationRunListener> listeners) {
        this.log = log;
        this.listeners = new ArrayList<>(listeners);
    }
    
    void starting() {
        for (SpringApplicationRunListener listener : this.listeners) {
            listener.starting();
        }
    }
    
    // ....
}

DefaultApplicationArguments()

public class DefaultApplicationArguments implements ApplicationArguments {

	private final Source source;

	private final String[] args;

	public DefaultApplicationArguments(String... args) {
		Assert.notNull(args, "Args must not be null");
		this.source = new Source(args);
		this.args = args;
	}
    
    private static class Source extends SimpleCommandLinePropertySource {

		Source(String[] args) {
			super(args);
		}

		// ...

	}
}

// 最终经过一系列,好几个super() 调用父类方法,走到了这里
public abstract class PropertySource<T> {

	protected final Log logger = LogFactory.getLog(getClass());

	protected final String name;

	protected final T source;


	/**
	 * Create a new {@code PropertySource} with the given name and source object.
	 * @param name the associated name
	 * @param source the source object
	 */
	public PropertySource(String name, T source) {
		Assert.hasText(name, "Property source name must contain at least one character");
		Assert.notNull(source, "Property source must not be null");
		this.name = name; // debug可以看到启动类传进来的参数最终生成了该对象,name为:"commandLineArgs"
		this.source = source;
	}
}

其他

ClassLoader

在SpringBoot源码中loadFactoryNames用的的次数比较多

public static List<String> loadFactoryNames(Class<?> factoryType, @Nullable ClassLoader classLoader) {
}

其中的ClassLoader有多个实现类

AppClassloader

  • 应用类加载器,也叫系统类加载器
  • 是我们平时接触最密切的类加载器, 主要负责加载classpath下的所有类
  • 平时我们用maven构建项目时,添加进pom文件中的依赖,最后都是由idea帮我们直接把依赖关联的jar包放到classPath下,并在运行时由AppClassloader帮我们把这些jar包中的class加载到内存中

未完待续...