前言:本系列文章非本人原创,转自:http://tengj.top/2017/04/24/springboot0/

正文

我们开发任何一个Spring Boot项目,都会用到如下的启动类

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

从上面代码可以看出,Annotation定义(@SpringBootApplication)和类定义(SpringApplication.run)最为耀眼,所以要揭开SpringBoot的神秘面纱,我们要从这两位开始就可以了。

SpringBootApplication背后的秘密

 1 package org.springframework.boot.autoconfigure;
 2 
 3 import java.lang.annotation.Annotation;
 4 import java.lang.annotation.Documented;
 5 import java.lang.annotation.Inherited;
 6 import java.lang.annotation.Retention;
 7 import java.lang.annotation.RetentionPolicy;
 8 import java.lang.annotation.Target;
 9 import org.springframework.boot.SpringBootConfiguration;
10 import org.springframework.context.annotation.ComponentScan;
11 import org.springframework.core.annotation.AliasFor;
12 
13 @Target({java.lang.annotation.ElementType.TYPE})
14 @Retention(RetentionPolicy.RUNTIME)
15 @Documented
16 @Inherited
17 @SpringBootConfiguration
18 @EnableAutoConfiguration
19 @ComponentScan(excludeFilters={@org.springframework.context.annotation.ComponentScan.Filter(type=org.springframework.context.annotation.FilterType.CUSTOM, classes={org.springframework.boot.context.TypeExcludeFilter.class}), @org.springframework.context.annotation.ComponentScan.Filter(type=org.springframework.context.annotation.FilterType.CUSTOM, classes={AutoConfigurationExcludeFilter.class})})
20 public @interface SpringBootApplication
21 {
22   @AliasFor(annotation=EnableAutoConfiguration.class)
23   Class<?>[] exclude() default {};
24   
25   @AliasFor(annotation=EnableAutoConfiguration.class)
26   String[] excludeName() default {};
27   
28   @AliasFor(annotation=ComponentScan.class, attribute="basePackages")
29   String[] scanBasePackages() default {};
30   
31   @AliasFor(annotation=ComponentScan.class, attribute="basePackageClasses")
32   Class<?>[] scanBasePackageClasses() default {};
33 }
34 
35 /* Location:           C:\Users\Administrator\.m2\repository\org\springframework\boot\spring-boot-autoconfigure\2.1.8.RELEASE\spring-boot-autoconfigure-2.1.8.RELEASE.jar
36  * Qualified Name:     org.springframework.boot.autoconfigure.SpringBootApplication
37  * Java Class Version: 8 (52.0)
38  * JD-Core Version:    0.7.0.1
39  */

虽然定义使用了多个Annotation进行了原信息标注,但实际上重要的只有三个Annotation:

  • @Configuration(@SpringBootConfiguration点开查看发现里面还是应用了@Configuration)
  • @EnableAutoConfiguration
  • @ComponentScan

所以,如果我们使用如下的SpringBoot启动类,整个SpringBoot应用依然可以与之前的启动类功能对等:

1 @Configuration
2 @EnableAutoConfiguration
3 @ComponentScan
4 public class Application {
5     public static void main(String[] args) {
6         SpringApplication.run(Application.class, args);
7     }
8 }

每次写这3个比较累,所以写一个@SpringBootApplication方便点。接下来分别介绍这3个Annotation。

@Configuration

这里的@Configuration对我们来说不陌生,它就是JavaConfig形式的Spring Ioc容器的配置类使用的那个@Configuration,SpringBoot社区推荐使用基于JavaConfig的配置形式,所以,这里的启动类标注了@Configuration之后,本身其实也是一个IoC容器的配置类。
举几个简单例子回顾下,XML跟config配置方式的区别:

  1、表达形式层面

  基于XML配置的方式是这样:

1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
5        default-lazy-init="true">
6     <!--bean定义-->
7 </beans>

  基于JavaConfig的配置方式是这样:

1 @Configuration
2 public class MockConfiguration{
3     //bean定义
4 }

  任何一个标注了@Configuration的Java类定义都是一个JavaConfig配置类。

  2、注册bean定义层面

  基于XML的配置形式是这样:

1 <bean id="mockService" class="..MockServiceImpl">
2     ...
3 </bean>

  基于JavaConfig的配置形式是这样的:

1 @Configuration
2 public class MockConfiguration{
3     @Bean
4     public MockService mockService(){
5         return new MockServiceImpl();
6     }
7 }

  任何一个标注了@Bean的方法,其返回值将作为一个bean定义注册到Spring的IoC容器,方法名将默认成该bean定义的id。

  3、表达依赖注入关系层面

  为了表达bean与bean之间的依赖关系,在XML形式中一般是这样:

1 <bean id="mockService" class="..MockServiceImpl">
2     <propery name ="dependencyService" ref="dependencyService" />
3 </bean>
4 
5 <bean id="dependencyService" class="DependencyServiceImpl></bean>

  基于JavaConfig的配置形式是这样的:

 1 @Configuration
 2 public class MockConfiguration{
 3     @Bean
 4     public MockService mockService(){
 5         return new MockServiceImpl(dependencyService());
 6     }
 7     
 8     @Bean
 9     public DependencyService dependencyService(){
10         return new DependencyServiceImpl();
11     }
12 }

  如果一个bean的定义依赖其他bean,则直接调用对应的JavaConfig类中依赖bean的创建方法就可以了。

@ComponentScan

@ComponentScan这个注解在Spring中很重要,它对应XML配置中的元素,@ComponentScan的功能其实就是自动扫描并加载符合条件的组件(比如@Component和@Repository等)或者bean定义,最终将这些bean定义加载到IoC容器中

我们可以通过basePackages等属性来细粒度的定制@ComponentScan自动扫描的范围,如果不指定,则默认Spring框架实现会从声明@ComponentScan所在类的package进行扫描。

注:所以SpringBoot的启动类最好是放在root package下,因为默认不指定basePackages。

@EnableAutoConfiguration

个人感觉@EnableAutoConfiguration这个Annotation最为重要,所以放在最后来解读,大家是否还记得Spring框架提供的各种名字为@Enable开头的Annotation定义?比如@EnableScheduling、@EnableCaching、@EnableMBeanExport等,@EnableAutoConfiguration的理念和做事方式其实一脉相承,简单概括一下就是,借助@Import的支持,收集和注册特定场景相关的bean定义

  • @EnableScheduling是通过@Import将Spring调度框架相关的bean定义都加载到IoC容器。
  • @EnableMBeanExport是通过@Import将JMX相关的bean定义加载到IoC容器。

而@EnableAutoConfiguration也是借助@Import的帮助,将所有符合自动配置条件的bean定义加载到IoC容器,仅此而已!

@EnableAutoConfiguration作为一个复合Annotation,其自身定义关键信息如下:

  1 /*
  2  * Copyright 2012-2019 the original author or authors.
  3  *
  4  * Licensed under the Apache License, Version 2.0 (the "License");
  5  * you may not use this file except in compliance with the License.
  6  * You may obtain a copy of the License at
  7  *
  8  *      https://www.apache.org/licenses/LICENSE-2.0
  9  *
 10  * Unless required by applicable law or agreed to in writing, software
 11  * distributed under the License is distributed on an "AS IS" BASIS,
 12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 13  * See the License for the specific language governing permissions and
 14  * limitations under the License.
 15  */
 16 
 17 package org.springframework.boot.autoconfigure;
 18 
 19 import java.lang.annotation.Documented;
 20 import java.lang.annotation.ElementType;
 21 import java.lang.annotation.Inherited;
 22 import java.lang.annotation.Retention;
 23 import java.lang.annotation.RetentionPolicy;
 24 import java.lang.annotation.Target;
 25 
 26 import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
 27 import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
 28 import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
 29 import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
 30 import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
 31 import org.springframework.context.annotation.Conditional;
 32 import org.springframework.context.annotation.Configuration;
 33 import org.springframework.context.annotation.Import;
 34 import org.springframework.core.io.support.SpringFactoriesLoader;
 35 
 36 /**
 37  * Enable auto-configuration of the Spring Application Context, attempting to guess and
 38  * configure beans that you are likely to need. Auto-configuration classes are usually
 39  * applied based on your classpath and what beans you have defined. For example, if you
 40  * have {@code tomcat-embedded.jar} on your classpath you are likely to want a
 41  * {@link TomcatServletWebServerFactory} (unless you have defined your own
 42  * {@link ServletWebServerFactory} bean).
 43  * <p>
 44  * When using {@link SpringBootApplication}, the auto-configuration of the context is
 45  * automatically enabled and adding this annotation has therefore no additional effect.
 46  * <p>
 47  * Auto-configuration tries to be as intelligent as possible and will back-away as you
 48  * define more of your own configuration. You can always manually {@link #exclude()} any
 49  * configuration that you never want to apply (use {@link #excludeName()} if you don't
 50  * have access to them). You can also exclude them via the
 51  * {@code spring.autoconfigure.exclude} property. Auto-configuration is always applied
 52  * after user-defined beans have been registered.
 53  * <p>
 54  * The package of the class that is annotated with {@code @EnableAutoConfiguration},
 55  * usually via {@code @SpringBootApplication}, has specific significance and is often used
 56  * as a 'default'. For example, it will be used when scanning for {@code @Entity} classes.
 57  * It is generally recommended that you place {@code @EnableAutoConfiguration} (if you're
 58  * not using {@code @SpringBootApplication}) in a root package so that all sub-packages
 59  * and classes can be searched.
 60  * <p>
 61  * Auto-configuration classes are regular Spring {@link Configuration} beans. They are
 62  * located using the {@link SpringFactoriesLoader} mechanism (keyed against this class).
 63  * Generally auto-configuration beans are {@link Conditional @Conditional} beans (most
 64  * often using {@link ConditionalOnClass @ConditionalOnClass} and
 65  * {@link ConditionalOnMissingBean @ConditionalOnMissingBean} annotations).
 66  *
 67  * @author Phillip Webb
 68  * @author Stephane Nicoll
 69  * @since 1.0.0
 70  * @see ConditionalOnBean
 71  * @see ConditionalOnMissingBean
 72  * @see ConditionalOnClass
 73  * @see AutoConfigureAfter
 74  * @see SpringBootApplication
 75  */
 76 @Target(ElementType.TYPE)
 77 @Retention(RetentionPolicy.RUNTIME)
 78 @Documented
 79 @Inherited
 80 @AutoConfigurationPackage
 81 @Import(AutoConfigurationImportSelector.class)
 82 public @interface EnableAutoConfiguration {
 83 
 84     String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";
 85 
 86     /**
 87      * Exclude specific auto-configuration classes such that they will never be applied.
 88      * @return the classes to exclude
 89      */
 90     Class<?>[] exclude() default {};
 91 
 92     /**
 93      * Exclude specific auto-configuration class names such that they will never be
 94      * applied.
 95      * @return the class names to exclude
 96      * @since 1.3.0
 97      */
 98     String[] excludeName() default {};
 99 
100 }

其中,最关键的要属@Import(EnableAutoConfigurationImportSelector.class),借助EnableAutoConfigurationImportSelector,@EnableAutoConfiguration可以帮助SpringBoot应用将所有符合条件的@Configuration配置都加载到当前SpringBoot创建并使用的IoC容器。

借助于Spring框架原有的一个工具类:SpringFactoriesLoader的支持,@EnableAutoConfiguration可以智能的自动配置功效才得以大功告成!

 

 

 自动配置幕后英雄:SpringFactoriesLoader详解
SpringFactoriesLoader属于Spring框架私有的一种扩展方案,其主要功能就是从指定的配置文件META-INF/spring.factories加载配置。

  1 /*
  2  * Copyright 2002-2018 the original author or authors.
  3  *
  4  * Licensed under the Apache License, Version 2.0 (the "License");
  5  * you may not use this file except in compliance with the License.
  6  * You may obtain a copy of the License at
  7  *
  8  *      https://www.apache.org/licenses/LICENSE-2.0
  9  *
 10  * Unless required by applicable law or agreed to in writing, software
 11  * distributed under the License is distributed on an "AS IS" BASIS,
 12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 13  * See the License for the specific language governing permissions and
 14  * limitations under the License.
 15  */
 16 
 17 package org.springframework.core.io.support;
 18 
 19 import java.io.IOException;
 20 import java.net.URL;
 21 import java.util.ArrayList;
 22 import java.util.Collections;
 23 import java.util.Enumeration;
 24 import java.util.List;
 25 import java.util.Map;
 26 import java.util.Properties;
 27 
 28 import org.apache.commons.logging.Log;
 29 import org.apache.commons.logging.LogFactory;
 30 
 31 import org.springframework.core.annotation.AnnotationAwareOrderComparator;
 32 import org.springframework.core.io.UrlResource;
 33 import org.springframework.lang.Nullable;
 34 import org.springframework.util.Assert;
 35 import org.springframework.util.ClassUtils;
 36 import org.springframework.util.ConcurrentReferenceHashMap;
 37 import org.springframework.util.LinkedMultiValueMap;
 38 import org.springframework.util.MultiValueMap;
 39 import org.springframework.util.ReflectionUtils;
 40 import org.springframework.util.StringUtils;
 41 
 42 /**
 43  * General purpose factory loading mechanism for internal use within the framework.
 44  *
 45  * <p>{@code SpringFactoriesLoader} {@linkplain #loadFactories loads} and instantiates
 46  * factories of a given type from {@value #FACTORIES_RESOURCE_LOCATION} files which
 47  * may be present in multiple JAR files in the classpath. The {@code spring.factories}
 48  * file must be in {@link Properties} format, where the key is the fully qualified
 49  * name of the interface or abstract class, and the value is a comma-separated list of
 50  * implementation class names. For example:
 51  *
 52  * <pre class="code">example.MyService=example.MyServiceImpl1,example.MyServiceImpl2</pre>
 53  *
 54  * where {@code example.MyService} is the name of the interface, and {@code MyServiceImpl1}
 55  * and {@code MyServiceImpl2} are two implementations.
 56  *
 57  * @author Arjen Poutsma
 58  * @author Juergen Hoeller
 59  * @author Sam Brannen
 60  * @since 3.2
 61  */
 62 public final class SpringFactoriesLoader {
 63 
 64     /**
 65      * The location to look for factories.
 66      * <p>Can be present in multiple JAR files.
 67      */
 68     public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";
 69 
 70 
 71     private static final Log logger = LogFactory.getLog(SpringFactoriesLoader.class);
 72 
 73     private static final Map<ClassLoader, MultiValueMap<String, String>> cache = new ConcurrentReferenceHashMap<>();
 74 
 75 
 76     private SpringFactoriesLoader() {
 77     }
 78 
 79 
 80     /**
 81      * Load and instantiate the factory implementations of the given type from
 82      * {@value #FACTORIES_RESOURCE_LOCATION}, using the given class loader.
 83      * <p>The returned factories are sorted through {@link AnnotationAwareOrderComparator}.
 84      * <p>If a custom instantiation strategy is required, use {@link #loadFactoryNames}
 85      * to obtain all registered factory names.
 86      * @param factoryClass the interface or abstract class representing the factory
 87      * @param classLoader the ClassLoader to use for loading (can be {@code null} to use the default)
 88      * @throws IllegalArgumentException if any factory implementation class cannot
 89      * be loaded or if an error occurs while instantiating any factory
 90      * @see #loadFactoryNames
 91      */
 92     public static <T> List<T> loadFactories(Class<T> factoryClass, @Nullable ClassLoader classLoader) {
 93         Assert.notNull(factoryClass, "'factoryClass' must not be null");
 94         ClassLoader classLoaderToUse = classLoader;
 95         if (classLoaderToUse == null) {
 96             classLoaderToUse = SpringFactoriesLoader.class.getClassLoader();
 97         }
 98         List<String> factoryNames = loadFactoryNames(factoryClass, classLoaderToUse);
 99         if (logger.isTraceEnabled()) {
100             logger.trace("Loaded [" + factoryClass.getName() + "] names: " + factoryNames);
101         }
102         List<T> result = new ArrayList<>(factoryNames.size());
103         for (String factoryName : factoryNames) {
104             result.add(instantiateFactory(factoryName, factoryClass, classLoaderToUse));
105         }
106         AnnotationAwareOrderComparator.sort(result);
107         return result;
108     }
109 
110     /**
111      * Load the fully qualified class names of factory implementations of the
112      * given type from {@value #FACTORIES_RESOURCE_LOCATION}, using the given
113      * class loader.
114      * @param factoryClass the interface or abstract class representing the factory
115      * @param classLoader the ClassLoader to use for loading resources; can be
116      * {@code null} to use the default
117      * @throws IllegalArgumentException if an error occurs while loading factory names
118      * @see #loadFactories
119      */
120     public static List<String> loadFactoryNames(Class<?> factoryClass, @Nullable ClassLoader classLoader) {
121         String factoryClassName = factoryClass.getName();
122         return loadSpringFactories(classLoader).getOrDefault(factoryClassName, Collections.emptyList());
123     }
124 
125     private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) {
126         MultiValueMap<String, String> result = cache.get(classLoader);
127         if (result != null) {
128             return result;
129         }
130 
131         try {
132             Enumeration<URL> urls = (classLoader != null ?
133                     classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :
134                     ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));
135             result = new LinkedMultiValueMap<>();
136             while (urls.hasMoreElements()) {
137                 URL url = urls.nextElement();
138                 UrlResource resource = new UrlResource(url);
139                 Properties properties = PropertiesLoaderUtils.loadProperties(resource);
140                 for (Map.Entry<?, ?> entry : properties.entrySet()) {
141                     String factoryClassName = ((String) entry.getKey()).trim();
142                     for (String factoryName : StringUtils.commaDelimitedListToStringArray((String) entry.getValue())) {
143                         result.add(factoryClassName, factoryName.trim());
144                     }
145                 }
146             }
147             cache.put(classLoader, result);
148             return result;
149         }
150         catch (IOException ex) {
151             throw new IllegalArgumentException("Unable to load factories from location [" +
152                     FACTORIES_RESOURCE_LOCATION + "]", ex);
153         }
154     }
155 
156     @SuppressWarnings("unchecked")
157     private static <T> T instantiateFactory(String instanceClassName, Class<T> factoryClass, ClassLoader classLoader) {
158         try {
159             Class<?> instanceClass = ClassUtils.forName(instanceClassName, classLoader);
160             if (!factoryClass.isAssignableFrom(instanceClass)) {
161                 throw new IllegalArgumentException(
162                         "Class [" + instanceClassName + "] is not assignable to [" + factoryClass.getName() + "]");
163             }
164             return (T) ReflectionUtils.accessibleConstructor(instanceClass).newInstance();
165         }
166         catch (Throwable ex) {
167             throw new IllegalArgumentException("Unable to instantiate factory class: " + factoryClass.getName(), ex);
168         }
169     }
170 
171 }

配合@EnableAutoConfiguration使用的话,它更多是提供一种配置查找的功能支持,即根据@EnableAutoConfiguration的完整类名org.springframework.boot.autoconfigure.EnableAutoConfiguration作为查找的Key,获取对应的一组@Configuration类

 

 

 上图就是从SpringBoot的spring-boot-autoconfigure-2.1.8.RELEASE.jar依赖包中的META-INF/spring.factories配置文件中摘录的一段内容,可以很好地说明问题。

所以,@EnableAutoConfiguration自动配置的魔法骑士就变成了:从classpath中搜寻所有的META-INF/spring.factories配置文件,并将其中org.springframework.boot.autoconfigure.EnableutoConfiguration对应的配置项通过反射(Java Refletion)实例化为对应的标注了@Configuration的JavaConfig形式的IoC容器配置类,然后汇总为一个并加载到IoC容器。

深入探索SpringApplication执行流程

SpringApplication的run方法的实现是我们本次旅程的主要线路,该方法的主要流程大体可以归纳如下:

1) 如果我们使用的是SpringApplication的静态run方法,那么,这个方法里面首先要创建一个SpringApplication对象实例,然后调用这个创建好的SpringApplication的实例方法。在SpringApplication实例初始化的时候,它会提前做几件事情:

  • 根据classpath里面是否存在某个特征类(org.springframework.web.context.ConfigurableWebApplicationContext)来决定是否应该创建一个为Web应用使用的ApplicationContext类型。
  • 使用SpringFactoriesLoader在应用的classpath中查找并加载所有可用的ApplicationContextInitializer。
  • 使用SpringFactoriesLoader在应用的classpath中查找并加载所有可用的ApplicationListener。
  • 推断并设置main方法的定义类。

2) SpringApplication实例初始化完成并且完成设置后,就开始执行run方法的逻辑了,方法执行伊始,首先遍历执行所有通过SpringFactoriesLoader可以查找到并加载的SpringApplicationRunListener。调用它们的started()方法,告诉这些SpringApplicationRunListener,“嘿,SpringBoot应用要开始执行咯!”。

3) 创建并配置当前Spring Boot应用将要使用的Environment(包括配置要使用的PropertySource以及Profile)。

4) 遍历调用所有SpringApplicationRunListener的environmentPrepared()的方法,告诉他们:“当前SpringBoot应用使用的Environment准备好了咯!”。

5) 如果SpringApplication的showBanner属性被设置为true,则打印banner。

6) 根据用户是否明确设置了applicationContextClass类型以及初始化阶段的推断结果,决定该为当前SpringBoot应用创建什么类型的ApplicationContext并创建完成,然后根据条件决定是否添加ShutdownHook,决定是否使用自定义的BeanNameGenerator,决定是否使用自定义的ResourceLoader,当然,最重要的,将之前准备好的Environment设置给创建好的ApplicationContext使用。

7) ApplicationContext创建好之后,SpringApplication会再次借助SpringFactoriesLoader,查找并加载classpath中所有可用的ApplicationContextInitializer,然后遍历调用这些ApplicationContextInitializer的initialize(applicationContext)方法来对已经创建好的ApplicationContext进行进一步的处理。

8) 遍历调用所有SpringApplicationRunListener的contextPrepared()方法。

9) 最核心的一步,将之前通过@EnableAutoConfiguration获取的所有配置以及其他形式的IoC容器配置加载到已经准备完毕的ApplicationContext。

10) 遍历调用所有SpringApplicationRunListener的contextLoaded()方法。

11) 调用ApplicationContext的refresh()方法,完成IoC容器可用的最后一道工序。

12) 查找当前ApplicationContext中是否注册有CommandLineRunner,如果有,则遍历执行它们。

13) 正常情况下,遍历执行SpringApplicationRunListener的finished()方法。(如果整个过程出现异常,则依然调用所有SpringApplicationRunListener的finished()方法,只不过这种情况下会将异常信息一并传入处理)
去除事件通知点后,整个流程如下:

 

 

 

总结

到此,SpringBoot的核心组件完成了基本的解析,综合来看,大部分都是Spring框架背后的一些概念和实践方式,SpringBoot只是在这些概念和实践上对特定的场景事先进行了固化和升华,而也恰恰是这些固化让我们开发基于Sping框架的应用更加方便高效。

参考

参考了《SpringBoot揭秘快速构建为服务体系》这本书的第三章,感兴趣的可以查阅。

 

posted on 2019-09-30 14:17  菜鸟麻花  阅读(203)  评论(0编辑  收藏  举报