01|项目示例

基于Spring boot构建一个简单的web项目

  • 1、引入依赖 ```java <?xml version=”1.0” encoding=”UTF-8”?> <project xmlns=”http://maven.apache.org/POM/4.0.0“ xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance

    1. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

    4.0.0 white.colde spring-boot-study 0.0.1-SNAPSHOT

    spring-boot-study

    1. <java.version>11</java.version>

    org.springframework.boot spring-boot-starter-parent 2.4.1 org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-maven-plugin

  1. - 2、创建测试接口
  2. ```java
  3. @RestController
  4. public class TestController {
  5. @GetMapping
  6. public String index(){
  7. return "hello spring boot";
  8. }
  9. }
  • 3、创建启动类 ```java @SpringBootApplication public class SpringBootStudyApplication {

    public static void main(String[] args) {

    1. SpringApplication.run(SpringBootStudyApplication.class, args);

    }

}

  1. <a name="YXNcO"></a>
  2. ## 02|IoC容器源码解析
  3. <a name="2F6J4"></a>
  4. ### 2.1|核心类
  5. <a name="xA2H7"></a>
  6. #### 1、SpringApplication
  7. SpringBoot应用入口类,核心方法如下:
  8. ```java
  9. public class SpringApplication{
  10. public ConfigurableApplicationContext run(String... args) {
  11. StopWatch stopWatch = new StopWatch();
  12. stopWatch.start();
  13. DefaultBootstrapContext bootstrapContext = createBootstrapContext();
  14. ConfigurableApplicationContext context = null;
  15. configureHeadlessProperty();
  16. SpringApplicationRunListeners listeners = getRunListeners(args);
  17. listeners.starting(bootstrapContext, this.mainApplicationClass);
  18. try {
  19. ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
  20. ConfigurableEnvironment environment = prepareEnvironment(listeners, bootstrapContext, applicationArguments);
  21. configureIgnoreBeanInfo(environment);
  22. Banner printedBanner = printBanner(environment);
  23. // 创建应用上下文,会依据当前运行环境创建不同的应用上下文对象
  24. // 由于这里为web环境,即此处创建的是AnnotationConfigServletWebServerApplicationContext对象
  25. context = createApplicationContext();
  26. context.setApplicationStartup(this.applicationStartup);
  27. prepareContext(bootstrapContext, context, environment, listeners, applicationArguments, printedBanner);
  28. // 开始容器初始化,解析装载bean到容器当中
  29. refreshContext(context);
  30. afterRefresh(context, applicationArguments);
  31. stopWatch.stop();
  32. if (this.logStartupInfo) {
  33. new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
  34. }
  35. listeners.started(context);
  36. callRunners(context, applicationArguments);
  37. }
  38. catch (Throwable ex) {
  39. handleRunFailure(context, ex, listeners);
  40. throw new IllegalStateException(ex);
  41. }
  42. try {
  43. listeners.running(context);
  44. }
  45. catch (Throwable ex) {
  46. handleRunFailure(context, ex, null);
  47. throw new IllegalStateException(ex);
  48. }
  49. return context;
  50. }
  51. }

SpringApplication主要做以下几个工作:

  • 执行容器初始化前的一些准备工作,如运行环境推断、解析根配置类信息等
  • 创建应用上下文
  • 调用Context的refresh方法,执行容器初始化逻辑

    2、AnnotationConfigServletWebServerApplicationContext

    SpringBoot web环境下默认创建的上下文对象,其类图如下:
    image.png
    在SpringApplication创建了AnnotationConfigServletWebServerApplicationContext类的对象,并调用了其refresh方法,而refresh方法的具体实现是在其父类AbstractApplicationContext中。

    3、AbstractApplicationContext

    1. public abstract class AbstractApplicationContext extends DefaultResourceLoader
    2. implements ConfigurableApplicationContext {
    3. @Override
    4. public void refresh() throws BeansException, IllegalStateException {
    5. synchronized (this.startupShutdownMonitor) {
    6. StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");
    7. // Prepare this context for refreshing.
    8. prepareRefresh();
    9. // 获取实际BeanFactory,默认实现是ConfigurableListableBeanFactory
    10. // 该对象是在GenericApplicationContext的构造方法中初始化创建
    11. ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
    12. prepareBeanFactory(beanFactory);
    13. try {
    14. // 提供了一个钩子方法供子类可以在BeanFactory准备工作完成后进行相应的逻辑处理调用
    15. postProcessBeanFactory(beanFactory);
    16. StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
    17. // 实例化并调⽤实现了BeanFactoryPostProcessor接⼝的Bean
    18. invokeBeanFactoryPostProcessors(beanFactory);
    19. // 注册BeanPostProcessor(Bean的后置处理器),在创建bean的前后等执⾏
    20. registerBeanPostProcessors(beanFactory);
    21. beanPostProcess.end();
    22. // 初始化MessageSource组件(做国际化功能;消息绑定,消息解析)
    23. initMessageSource();
    24. // 初始化事件派发器
    25. initApplicationEventMulticaster();
    26. // ⼦类重写这个⽅法,在容器刷新的时候可以⾃定义逻辑
    27. onRefresh();
    28. // 注册应⽤的监听器。就是注册实现了ApplicationListener接⼝的监听器bean
    29. registerListeners();
    30. // 初始化所有剩下的非懒加载的单例Bean
    31. finishBeanFactoryInitialization(beanFactory);
    32. // 完成容器的初始化,发布事件
    33. finishRefresh();
    34. }
    35. catch (BeansException ex) {
    36. if (logger.isWarnEnabled()) {
    37. logger.warn("Exception encountered during context initialization - " +
    38. "cancelling refresh attempt: " + ex);
    39. }
    40. // Destroy already created singletons to avoid dangling resources.
    41. destroyBeans();
    42. // Reset 'active' flag.
    43. cancelRefresh(ex);
    44. // Propagate exception to caller.
    45. throw ex;
    46. }
    47. finally {
    48. // Reset common introspection caches in Spring's core, since we
    49. // might not ever need metadata for singleton beans anymore...
    50. resetCommonCaches();
    51. contextRefresh.end();
    52. }
    53. }
    54. }
    55. }

    4、DefaultListableBeanFactory

    GenericApplicationContext构造方法中创建了一个DefaultListableBeanFactory类的实例,DefaultListableBeanFactory是Spring注册和加载Bean的默认实现类,ApplicationContext有关操作皆委托由DefaultListableBeanFactory进行实现,其类图如下:
    image.png

  • AliasRegistry:定义对alias的简单增删改等操作

  • SimpleAliasRegistry:主要使用map作为alias的缓存,并对接口AliasRegistry进行实现
  • SingletonBeanRegistry:定义对单例Bean的注册及获取
  • BeanFactory:定义了获取Bean及Bean的各种属性
  • HierarchicalBeanFactory:包含层次结构的BeanFactory,在BeanFactory的基础上增加了对parentFactory的支持
  • BeanDefinitionRegistry:定义对BeanDefinition的各种增删改操作
  • FactoryBeanRegistrySupport:在DefaultSingletonBeanRegistry基础上增加了对FactoryBean的特殊处理功能
  • ConfigurableBeanFactory:提供配置Factory的各种方法
  • ListableBeanFactory:根据各种条件获取Bean的配置清单
  • AbstractBeanFactory:综合FactoryBeanRegistrySupport和ConfigurationBeanFactory的功能
  • AutowireCapableBeanFactory:提供创建Bean、自动注入、初始化
  • AbstractAutowireCapableBeanFactory:综合AbstractBeanFactory并对AutowireCapableBeanFactory进行实现
  • ConfigurableListableBeanFactory:BeanFactory配置清单,指定忽略类型及接口等
  • DefaultListableBeanFactory:综合上面的所有功能,本身提供对Bean注册后的一些处理功能