Springboot2.0的启动详解

抄袭自:Spring Boot1.3.3启动流程详解

0.先来说说启动类的注解

1
2
3
4
5
6
@SpringBootApplication
public class LearnApplication {
public static void main(String[] args) {
SpringApplication.run(LearnApplication.class, args);
}
}

其中,类注解@SpringBootApplication的实现为

1
2
3
4
5
6
7
8
9
10
11
12
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {
@Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {

}

其中,@SpringBootConfiguration,@EnableAutoConfiguration@ComponentScan为主要注解,用这三个注解代替启动类上的@SpringBootApplication也能使工程正常运行。

详解@SpringBootConfiguration,@EnableAutoConfiguration和@ComponentScan

三个注解主要做一件事:注册bean到spring容器,通过不同条件不同方式来完成。

  • @SpringBootConfiguration
    其底层为
    1
    2
    3
    4
    5
    6
    7
    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Configuration
    public @interface SpringBootConfiguration {

    }
1
2
3
4
5
6
	
```@Configuration```是等同于String的xml文件配合```@Bean```注解,可以配置需要Spring容器管理的bean。

* 自动配置 @EnableAutoConfiguration
注解源码

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
// 主要注解,通过导入方式,将制定class注册到Spring容器
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
    
}
1
2
3
4
5
6
7
	
```@EnableAutoConfiguration```从classpath中搜索所有的```META-INF/spring.factories```配置文件,将```org.springframework.boot.autoconfigure.EnableutoConfiguration```对应的配置项通过反射实例化为对应标注了```@Configuartion```的JavaConfig形式的IoC容器配置类,汇总成一个,加载到IoC容器。

* 组件扫描 @ComponentScan

注解源码

@Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Documented @Repeatable(ComponentScans.class) public @interface ComponentScan { // 对应的包扫描路径 @AliasFor("basePackages") String[] value() default {}; // 对应的包扫描路径 @AliasFor("value") String[] basePackages() default {}; // 指定具体扫描类 Class<?>[] basePackageClasses() default {}; // 对应bean名称生成器,默认BeanNameGenerator.class Class<? extends BeanNameGenerator> nameGenerator() default BeanNameGenerator.class; // 对应监测到的bean的scope范围 Class<? extends ScopeMetadataResolver> scopeResolver() default AnnotationScopeMetadataResolver.class; // 为监测到的组件生成代理 ScopedProxyMode scopedProxy() default ScopedProxyMode.DEFAULT; // 控制符合组件检测条件的类文件,默认在包扫描下 String resourcePattern() default ClassPathScanningCandidateComponentProvider.DEFAULT_RESOURCE_PATTERN; // 是否对带@Component,@Repository,@Service,@Controller自动检测,默认开启 boolean useDefaultFilters() default true; // 指定定义Filter满足条件的组件 Filter[] includeFilters() default {}; // 排除定义Filter不满足条件的组件 Filter[] excludeFilters() default {}; // 扫描到的类进行懒加载,默认关闭 boolean lazyInit() default false; }
1
2
3
4
5
6
7
8
	
```@ComponentScan```该注解告知Spring要扫描那些类或包,默认扫描该注解所在包及子包下所有类。
所以在SpringBoot项目中,启动类放在顶层目录中,以便扫描到所有类。
扫描特定注解注释的类,将其注册到Spring容器中。

### 1.由如下代码启动
在这个main方法中,调用了SpringApplication的静态run方法,并将Application类对象和main方法的参数args作为参数传递了进去。

public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}

1
2
### 2.在这个静态方法中,创建SpringApplication对象,并调用该对象的run方法。

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);
}

1
2
3
4
5
6
7
8
9
10
### 3.进入SpringApplication类中看到  
构造函数中,初始化SpringApplication对象的成员变量:

* `resourceLoader `:由传参获得
* `primarySources`:由传参获得
* `webApplicationType`
* `initializers`
* `listeners`
* `mainApplicationClass`

/**
 * 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
 */
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
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
    this.resourceLoader = resourceLoader;
    Assert.notNull(primarySources, "PrimarySources must not be null");
    this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
    this.webApplicationType = deduceWebApplicationType();
    setInitializers((Collection) getSpringFactoriesInstances(
            ApplicationContextInitializer.class));
    setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
    this.mainApplicationClass = deduceMainApplicationClass();
}
1
2
3

#### 3.1 webApplicationType:通过类判断应用类型

/**
 * The class name of application context that will be used by default for reactive web
 * environments.
 */
public static final String DEFAULT_REACTIVE_WEB_CONTEXT_CLASS = "org.springframework."
        + "boot.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContext";

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

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

public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
    ...
    this.webApplicationType = deduceWebApplicationType();
    ...
}
1
2
3

`deduceWebApplicationType`方法返回的是`WebApplicationType`(表示web应用类型的枚举类),通过查看类是否存在数组中所包含的类来判断应用类型

private WebApplicationType deduceWebApplicationType() {
    // 响应式web应用
    if (ClassUtils.isPresent(REACTIVE_WEB_ENVIRONMENT_CLASS, null)
            && !ClassUtils.isPresent(MVC_WEB_ENVIRONMENT_CLASS, null)) {
        return WebApplicationType.REACTIVE;
    }
    for (String className : WEB_ENVIRONMENT_CLASSES) {
        // 不是web应用
        if (!ClassUtils.isPresent(className, null)) {
            return WebApplicationType.NONE;
        }
    }
    // 基于servlet的web应用
    return WebApplicationType.SERVLET;
}
1
2
3
4

#### 3.2 setInitializers:设置initializers成员变量


public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
    ...
    setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
    ...
}

/**
 * Sets the {@link ApplicationContextInitializer} that will be applied to the Spring
 */
public void setInitializers(
        Collection<? extends ApplicationContextInitializer<?>> initializers) {
    this.initializers = new ArrayList<>();
    this.initializers.addAll(initializers);
}
1
2
3
4

调用`getSpringFactoriesInstances`获取`ApplicationContextInitializer`类型对象的列表,该方法中,通过`SpringFactoriesLoader.loadFactoryNames(type, classLoader)`获取所有Spring Factories名字,再调用`createSpringFactoriesInstances(type, parameterTypes,
classLoader, args, names)`根据type创建对象,再返回一个List<type>

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 = Thread.currentThread().getContextClassLoader();
    // 使用名字保证唯一性,避免重复冲突
    Set<String> names = new LinkedHashSet<>(
            SpringFactoriesLoader.loadFactoryNames(type, classLoader));
    List<T> instances = createSpringFactoriesInstances(type, parameterTypes,
            classLoader, args, names);
    AnnotationAwareOrderComparator.sort(instances);
    return instances;
}
1

public static List<String> loadFactoryNames(Class<?> factoryClass, @Nullable ClassLoader classLoader) {
    String factoryClassName = factoryClass.getName();
    return (List)loadSpringFactories(classLoader).getOrDefault(factoryClassName, Collections.emptyList());
}

private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) {
    MultiValueMap<String, String> result = (MultiValueMap)cache.get(classLoader);
    if (result != null) {
        return result;
    } else {
        try {
            Enumeration<URL> urls = classLoader != null ? classLoader.getResources("META-INF/spring.factories") : ClassLoader.getSystemResources("META-INF/spring.factories");
            LinkedMultiValueMap result = new LinkedMultiValueMap();

            while(urls.hasMoreElements()) {
                URL url = (URL)urls.nextElement();
                UrlResource resource = new UrlResource(url);
                Properties properties = PropertiesLoaderUtils.loadProperties(resource);
                Iterator var6 = properties.entrySet().iterator();

                while(var6.hasNext()) {
                    Entry<?, ?> entry = (Entry)var6.next();
                    List<String> factoryClassNames = Arrays.asList(StringUtils.commaDelimitedListToStringArray((String)entry.getValue()));
                    result.addAll((String)entry.getKey(), factoryClassNames);
                }
            }

            cache.put(classLoader, result);
            return result;
        } catch (IOException var9) {
            throw new IllegalArgumentException("Unable to load factories from location [META-INF/spring.factories]", var9);
        }
    }
}
1
2
3
4


其中,Spring Factories名字从如下路径读取

Enumeration urls = classLoader != null ? classLoader.getResources(“META-INF/spring.factories”) : ClassLoader.getSystemResources(“META-INF/spring.factories”);

1
2
3

成员变量会被初始化为如下5个类对象组成的list

Application Context Initializers

初始化ApplicationContext,在refresh前调用

org.springframework.context.ApplicationContextInitializer=\

为ApplicationContext添加检查配置,并在常见错误配置时打印警告信息BeanFactoryPostProcessor

org.springframework.boot.context.ConfigurationWarningsApplicationContextInitializer,\

为ApplicationContext设置id

org.springframework.boot.context.ContextIdApplicationContextInitializer,\

从ApplicationContext环境配置中读取Initializer并应用

org.springframework.boot.context.config.DelegatingApplicationContextInitializer,\

为ApplicationContext设置环境变量,以便单元测试中使用服务器正监听的端口号

org.springframework.boot.web.context.ServerPortInfoApplicationContextInitializer

1
2
3

通过`createSpringFactoriesInstances`创建ApplicationContextInitializer实例

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;
}
1
2
3
4
5

#### 3.3 setListeners:设置listeners成员变量

listeners成员变量是ApplicationListener<?>的集合

public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
    ...
    setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
    ...
}

/**
 * Sets the {@link ApplicationListener}s that will be applied to the SpringApplication
 * and registered with the {@link ApplicationContext}.     */
public void setListeners(Collection<? extends ApplicationListener<?>> listeners) {
    this.listeners = new ArrayList<>();
    this.listeners.addAll(listeners);
}
1
2
3

和成员变量initializers调用一样的方法,成员变量会被初始化为如下10个类对象组成的list

Application Listeners

观察者模式的监听器接口,监听各种ApplicationEvent

org.springframework.context.ApplicationListener=\

清缓存

org.springframework.boot.ClearCachesApplicationListener,\

父context关闭,关闭当前ApplicationContext

org.springframework.boot.builder.ParentContextCloserApplicationListener,\

当系统属性System.encoding与配置的spring编码不同时,打印错误信息,并终止系统启动

org.springframework.boot.context.FileEncodingApplicationListener,\

根据属性spring.output.ansi.enabled配置ANSI输出(彩色输出日志)

org.springframework.boot.context.config.AnsiOutputApplicationListener,\

搜索加载配置文件,并根据配置文件设置Environment与Application

org.springframework.boot.context.config.ConfigFileApplicationListener,\

加载并转发事件至context.listener.classes中配置的ApplicationLIstener

org.springframework.boot.context.config.DelegatingApplicationListener,\

程序正常启动成功:将classpath打印至debug日志

程序正常启动失败:将classpath打印至info日志

org.springframework.boot.context.logging.ClasspathLoggingApplicationListener,\

根据配置,适当的时候初始化与配置日志系统

org.springframework.boot.context.logging.LoggingApplicationListener,\

若classpath中存在类liquibase.servicelocator.ServiceLocator,替换成适用于springboot的版本

org.springframework.boot.liquibase.LiquibaseServiceLocatorApplicationListener

1
2
3
4
5
6
7



#### 3.4 deduceMainApplicationClass:

在deduceMainApplicationClass方法中,通过获取当前调用栈,找到入口方法main所在的类,并将其复制给SpringApplication对象的成员变量mainApplicationClass(即创建的`SpringApplication.class`)

public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
    ...
    this.mainApplicationClass = deduceMainApplicationClass();
}

private Class<?> deduceMainApplicationClass() {
    try {
        StackTraceElement[] stackTrace = new RuntimeException().getStackTrace();
        for (StackTraceElement stackTraceElement : stackTrace) {
            // 获取当前调用栈
            if ("main".equals(stackTraceElement.getMethodName())) {
                // 找到main方法所在类并返回
                return Class.forName(stackTraceElement.getClassName());
            }
        }
    }
    catch (ClassNotFoundException ex) {
        // Swallow and continue
    }
    return null;
}    
1
2
3
### 4.SpringApplication对象的run方法
以上为初始化过程,得到了一个SpringApplication对象,接下来将调用其静态`run`方法。SpringApplication对象的run方法创建并刷新ApplicationContext,按照执行顺序,介绍该方法所做的工作。

public static ConfigurableApplicationContext run(Class<?>[] primarySources,
        String[] args) {
    return new SpringApplication(primarySources).run(args);
}

public ConfigurableApplicationContext run(String... args) {
    // StopWatch是来自org.springframework.util的工具类,可以用来方便的记录程序的运行时间
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    
    ConfigurableApplicationContext context = null;
    Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
    
    // 设置headless模式
    configureHeadlessProperty();
    
    SpringApplicationRunListeners listeners = getRunListeners(args);
    listeners.starting();
    
    try {
        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);
        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, listeners, exceptionReporters, ex);
        throw new IllegalStateException(ex);
    }
    listeners.running(context);
    return context;
}
1
2
3
4
5

#### 4.1 headless模式

设置系统属性java.awt.headless

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

public ConfigurableApplicationContext run(String... args) {
    ...
    // 设置headless模式
    configureHeadlessProperty();
    ...
}

private void configureHeadlessProperty() {
    System.setProperty(SYSTEM_PROPERTY_JAVA_AWT_HEADLESS, System.getProperty(
            SYSTEM_PROPERTY_JAVA_AWT_HEADLESS, Boolean.toString(this.headless)));
}
1
2
3
4
5
6

#### 4.2 SpringApplicationRunListeners

在SpringApplication对象的run方法执行的不同阶段,去执行一些操作,并且这些操作是可配置的。
加载SpringApplicationRunListener时,使用的是跟加载ApplicationContextInitializer和ApplicationListener时一样的方法,加载内容如下:

Run Listeners

org.springframework.boot.SpringApplicationRunListener=\

RunListener是在SpringApplication对象的run方法执行到不同的阶段时,发布相应的event给SpringApplication对象的成员变量listeners中记录的事件监听器。

org.springframework.boot.context.event.EventPublishingRunListener

1

public ConfigurableApplicationContext run(String... args) {
    ...
    SpringApplicationRunListeners listeners = getRunListeners(args);
    listeners.starting();
    try {
        // 把main函数的args参数当做一个PropertySource来解析
        ApplicationArguments applicationArguments = new DefaultApplicationArguments(
                args);
        // 配置环境:读取执行配置文件:profiles与properties
        ConfigurableEnvironment environment = prepareEnvironment(listeners,
                applicationArguments);
        // 跳过特定Bean的配置
        configureIgnoreBeanInfo(environment);
        // banner打印
        Banner printedBanner = printBanner(environment);
        
        // 创建会话
        context = createApplicationContext();
        exceptionReporters = getSpringFactoriesInstances(
                SpringBootExceptionReporter.class,
                new Class[] { ConfigurableApplicationContext.class }, context);
        // 准备会话
        prepareContext(context, environment, listeners, applicationArguments,
                printedBanner);
        // 刷新会话
        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, listeners, exceptionReporters, ex);
        throw new IllegalStateException(ex);
    }
    listeners.running(context);
    return context;
}

private SpringApplicationRunListeners getRunListeners(String[] args) {
    Class<?>[] types = new Class<?>[] { SpringApplication.class, String[].class };
    return new SpringApplicationRunListeners(logger, getSpringFactoriesInstances(
            SpringApplicationRunListener.class, types, this, args));
}

```

Tips:Environment代表着程序运行的环境,主要包含了两种信息

  • profiles,用来描述哪些bean definitions是可用的
  • properties,用来描述系统的配置,其来源可能是配置文件、JVM属性文件、操作系统环境变量等等

再里面的方法就不点进去一一看了,大致酱。

版本命名规范

上家公司在发版时对tag的命名一直不是很规范,参考了各大网站及博客上的说明,做个笔记。

阅读更多

nginx

Nginx负载均衡有4种方案配置

阅读更多