您的位置:首页 > 编程语言 > Java开发

Springboot 源码解析(启动时)

2017-06-28 18:38 736 查看
@SpringBootApplication(exclude = {MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})

public class VoiceAssistantApplication {

public static void main(String[] args) throws UnknownHostException {

SpringApplication.run(VoiceAssistantApplication.class, args);

}

}

对于注解@SpringBootApplication:其源码如下

@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 : 表示Application作为sprig配置文件存在

@EnableAutoConfiguration: 启动spring boot内置的自动配置

@ComponentScan : 扫描bean,路径为Application类所在package以及package下的子路径,这里为 com.lkl.springboot,在spring boot中bean都放置在该路径已经子路径下。

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

@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

3

4

5

6

7

8

9

10

@SuppressWarnings(“deprecation”)

@Target(ElementType.TYPE)

@Retention(RetentionPolicy.RUNTIME)

@Documented

@Inherited

@AutoConfigurationPackage

@Import(EnableAutoConfigurationImportSelector.class)

public @interface EnableAutoConfiguration {



}

  

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

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

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

上图就是从SpringBoot的autoconfigure依赖包中的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会再次借助Spring-FactoriesLoader,查找并加载classpath中所有可用的ApplicationContext-Initializer,然后遍历调用这些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框架的应用更加方便高效。

@SpringBootApplication(exclude = {MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})

public class VoiceAssistantApplication {

public static void main(String[] args) throws UnknownHostException {

SpringApplication.run(VoiceAssistantApplication.class, args);

}

}

↓ 进入到SpringApplication类

//执行这里的run方法

↓new SpringApplication(sources)

↓进入初始化函数

0、将传入的VoiceAssistantApplication.class对象放入Set集合

1、deduceWebEnvironment()://推断是否为web环境

private static final String[] WEB_ENVIRONMENT_CLASSES = { “javax.servlet.Servlet”,

“org.springframework.web.context.ConfigurableWebApplicationContext” };

private boolean deduceWebEnvironment() {

for (String className : WEB_ENVIRONMENT_CLASSES) {

if (!ClassUtils.isPresent(className, null)) {

return false;

}

}

return true;

}

//说明:通过在classpath中查看是否存在WEB_ENVIRONMENT_CLASSES这个数组中所包含的所有类(实际上就是2个类),如果存在那么当前程序即是一个Web应用程序,反之则不然。

/**

* Determine whether the {@link Class} identified by the supplied name is present

* and can be loaded. Will return {@code false} if either the class or

* one of its dependencies is not present or cannot be loaded.

* @param className the name of the class to check

* @param classLoader the class loader to use

* (may be {@code null}, which indicates the default class loader)

* @return whether the specified class is present

*/

public static boolean isPresent(String className, ClassLoader classLoader) {

try {

forName(className, classLoader);//利用java的反射机制进行加载

return true;

}

catch (Throwable ex) {

// Class or one of its dependencies is not present…

return false;

}

}

2、setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));//创建ApplicationInitializer列表

private Collection

Initializers

org.springframework.context.ApplicationContextInitializer=\ 注意就是这个类,那个工厂就是根据这个类型进行加载,所以其实加载了只有下面的两个类

org.springframework.boot.autoconfigure.SharedMetadataReaderFactoryContextInitializer,\

org.springframework.boot.autoconfigure.logging.AutoConfigurationReportLoggingInitializer

步骤:

调用SpringFactoriesLoader.loadFactoryNames(type, classLoader)来获取所有Spring Factories的名字,(这里是获取了2个ApplicationContextInitializer实现类的全类名,见上面)

为每一个Spring Factories根据读取到的名字创建其对象。(这里创建了2个对象)

将创建好的对象列表排序并返回。

说明:

从所有jar获取所有的META-INF/spring-factories文件。(这里只有spring-boot-1.3.0.RELEASE.jar下有一个)

遍历每一个spring-factories文件,并获取其下key为factoryClass.getName()

至此,设置ApplicationContextInitialize就完成了。

总结:整个setInitializers实际上就是初始化了SpringApplication的属性List

Application Listeners

org.springframework.context.ApplicationListener=\

org.springframework.boot.autoconfigure.BackgroundPreinitializer

至此,整个setListeners方法结束,初始化了一个包含以上1个ApplicationListener实例的List集合。

4、this.mainApplicationClass = deduceMainApplicationClass();//初始化主类mainApplicationClass

private Class

Failure analyzers

org.springframework.boot.diagnostics.FailureAnalyzer=\

org.springframework.boot.autoconfigure.diagnostics.analyzer.NoSuchBeanDefinitionFailureAnalyzer,\

org.springframework.boot.autoconfigure.jdbc.DataSourceBeanCreationFailureAnalyzer,\

org.springframework.boot.autoconfigure.jdbc.HikariDriverConfigurationFailureAnalyzer

//ApplicationContext创建好之后,SpringApplication会再次借助Spring-FactoriesLoader,加载失败分析的类,主要用于处理失败情况

6、prepareContext(context, environment, listeners, applicationArguments,printedBanner);

private void prepareContext(ConfigurableApplicationContext context,

ConfigurableEnvironment environment, SpringApplicationRunListeners listeners,

ApplicationArguments applicationArguments, Banner printedBanner) {

context.setEnvironment(environment);

postProcessApplicationContext(context);

applyInitializers(context);

listeners.contextPrepared(context);

if (this.logStartupInfo) {

logStartupInfo(context.getParent() == null);

logStartupProfileInfo(context);

}

// Add boot specific singleton beans

context.getBeanFactory().registerSingleton(“springApplicationArguments”,

applicationArguments);

if (printedBanner != null) {

context.getBeanFactory().registerSingleton(“springBootBanner”, printedBanner);

}

// Load the sources

Set sources = getSources();

Assert.notEmpty(sources, “Sources must not be empty”);

load(context, sources.toArray(new Object[sources.size()]));

listeners.contextLoaded(context);

}

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

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

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

7、refreshContext(context);

private void refreshContext(ConfigurableApplicationContext context) {

refresh(context);

if (this.registerShutdownHook) {

try {

context.registerShutdownHook();

}

catch (AccessControlException ex) {

// Not allowed in some environments.

}

}

}

protected void refresh(ApplicationContext applicationContext) {

Assert.isInstanceOf(AbstractApplicationContext.class, applicationContext);

((AbstractApplicationContext) applicationContext).refresh();

}

注意:最终调用了spring的refresh()方法!

spring初始化Ioc容器很重要的一个方法是由ApplicationContext子接口ConfigurableApplicationContext提供的refresh(),这个方法的作用是创建加载Spring容器配置(包括.xml配置,property文件和数据库模式等)。下面是各个refresh()调用的各个方法的作用解析:

[java] view plain copy

1. @Override

2. public void refresh() throws BeansException, IllegalStateException {

3. synchronized (this.startupShutdownMonitor) {

4. // Prepare this context for refreshing.

5. prepareRefresh();

6.

7. // Tell the subclass to refresh the internal bean factory.

8. //主要是创建beanFactory,同时加载配置文件.xml中的beanDefinition

9. //通过String[] configLocations = getConfigLocations()获取资源路径,然后加载beanDefinition

10. ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

11.

12. // Prepare the bean factory for use in this context.

13. //给beanFactory注册一些标准组建,如ClassLoader,StandardEnvironment,BeanProcess

14. prepareBeanFactory(beanFactory);

15.

16. try {

17. // Allows post-processing of the bean factory in context subclasses.

18. //提供给子类实现一些postProcess的注册,如AbstractRefreshableWebApplicationContext注册一些Servlet相关的

19. //postProcess,真对web进行生命周期管理的Scope,通过registerResolvableDependency()方法注册指定ServletRequest,HttpSession,WebRequest对象的工厂方法

20. postProcessBeanFactory(beanFactory);

21.

22. // Invoke factory processors registered as beans in the context.

23. //调用所有BeanFactoryProcessor的postProcessBeanFactory()方法

24. invokeBeanFactoryPostProcessors(beanFactory);

25.

26. // Register bean processors that intercept bean creation.

27. //注册BeanPostProcessor,BeanPostProcessor作用是用于拦截Bean的创建

28. registerBeanPostProcessors(beanFactory);

29.

30. // Initialize message source for this context.

31. //初始化消息Bean

32. initMessageSource();

33.

34. // Initialize event multicaster for this context.

35. //初始化上下文的事件多播组建,ApplicationEvent触发时由multicaster通知给ApplicationListener

36. initApplicationEventMulticaster();

37.

38. // Initialize other special beans in specific context subclasses.

39. //ApplicationContext初始化一些特殊的bean

40. onRefresh();

41.

42. // Check for listener beans and register them.

43. //注册事件监听器,事件监听Bean统一注册到multicaster里头,ApplicationEvent事件触发后会由multicaster广播

44. registerListeners();

45.

46. // Instantiate all remaining (non-lazy-init) singletons.

47. //非延迟加载的单例Bean实例化

48. finishBeanFactoryInitialization(beanFactory);

49.

50. // Last step: publish corresponding event.

51. finishRefresh();

52. }

53.

54. catch (BeansException ex) {

55. logger.warn(“Exception encountered during context initialization - cancelling refresh attempt”, ex);

56.

57. // Destroy already created singletons to avoid dangling resources.

58. destroyBeans();

59.

60. // Reset ‘active’ flag.

61. cancelRefresh(ex);

62.

63. // Propagate exception to caller.

64. throw ex;

65. }

66. }

67. }

8、afterRefresh(context, applicationArguments);

/**

* Called after the context has been refreshed.

* @param context the application context

* @param args the application arguments

*/

protected void afterRefresh(ConfigurableApplicationContext context,

ApplicationArguments args) {

callRunners(context, args);

}

private void callRunners(ApplicationContext context, ApplicationArguments args) {

List runners = new ArrayList();

runners.addAll(context.getBeansOfType(ApplicationRunner.class).values());

runners.addAll(context.getBeansOfType(CommandLineRunner.class).values());//这两个类只有有类实现了他们的接口,便会在程序启动时执行二者的方法喽!二者除了参数不一样,感觉没多大差别

AnnotationAwareOrderComparator.sort(runners);

for (Object runner : new LinkedHashSet(runners)) {

if (runner instanceof ApplicationRunner) {

callRunner((ApplicationRunner) runner, args);

}

if (runner instanceof CommandLineRunner) {

callRunner((CommandLineRunner) runner, args);

}

}

}

public interface ApplicationRunner {

/**

* Callback used to run the bean.

* @param args incoming application arguments

* @throws Exception on error

*/

void run(ApplicationArguments args) throws Exception;

}

public interface CommandLineRunner {

/**

* Callback used to run the bean.

* @param args incoming main method arguments

* @throws Exception on error

*/

void run(String… args) throws Exception;

}

9、listeners.finished(context, null);

public void finished(ConfigurableApplicationContext context, Throwable exception) {

for (SpringApplicationRunListener listener : this.listeners) {

callFinishedListener(listener, context, exception);

}

}

//正常情况下,遍历执行SpringApplicationRunListener的finished()方法、(如果整个过程出现异常,则依然调用所有SpringApplicationRunListener的finished()方法,只不过这种情况下会将异常信息一并传入处理)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  string 源码