1.3 一个简单的启动类

2.源码大致解析
2.1 主方法(MAIN)
1.创建一个Spring应用 new SpringApplication(primarySources).run(args) 2.new SpringApplication public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) { 2.1 资源加载 this.resourceLoader = resourceLoader; Assert.notNull(primarySources, "PrimarySources must not be null"); 2.2 将主类放入linkedHastSet当中 this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources)); 2.3 应用类型的选择 this.webApplicationType = WebApplicationType.deduceFromClasspath(); 2.4 设置初始化(构造)器 setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class)); 2.5 设置(应用)监听器 setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class)); 2.6 配置应用的主方法所在类 this.mainApplicationClass = deduceMainApplicationClass(); }
3. run(args); public ConfigurableApplicationContext run(String... args) { 3.1 计时器开始 StopWatch stopWatch = new StopWatch(); stopWatch.start(); ConfigurableApplicationContext context = null; Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>(); 3.2 配置参数 configureHeadlessProperty(); 3.3 配置运行监听器 SpringApplicationRunListeners listeners = getRunListeners(args); 3.4 监听器开始工作 listeners.starting(); try { ApplicationArguments applicationArguments = new DefaultApplicationArguments(args); 3.5准备环境--监听器和应用参数 ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments); 3.6配置忽略的Bean信息 configureIgnoreBeanInfo(environment); 3.7打印图案 Banner printedBanner = printBanner(environment); 3.8 创建应用上下文 context = createApplicationContext(); 3.9 异常报告 exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[] { ConfigurableApplicationContext.class }, context); 3.10 准备上下文(将启动类注册到BeanDefinition) prepareContext(context, environment, listeners, applicationArguments, printedBanner); 3.11 刷新上下文 refreshContext(context); 3.12 刷新上下文善后 afterRefresh(context, applicationArguments); 3.13 计时器结束 stopWatch.stop(); if (this.logStartupInfo) { new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch); } 3.14 启动所有监听器 listeners.started(context); callRunners(context, applicationArguments); } catch (Throwable ex) { 3.15 处理运行失败 handleRunFailure(context, ex, exceptionReporters, listeners); throw new IllegalStateException(ex); } try { 3.16 将应用上下文传递给每一个监听器 listeners.running(context); } catch (Throwable ex) { handleRunFailure(context, ex, exceptionReporters, null); throw new IllegalStateException(ex); } return context; }
2.2 SPRINGBOOTAPPLICATOIN注解
- 基本属性 1.1 exclude 排除不需要自动配置的类 1.2 excludeName 排除不需要自动配置的类的类名 1.3 scanBasePackages 扫描基本包(被指定的包的子包也会包扫描到) 1.4 scanBasePackageClasses 扫描类所在包下的所有组件 2. 注解 2.1 SpringBootConfiguration 表明这个类提供一个Spring Boot Application(Indicates that a class provides Spring Boot application) 2.2 EnableAutoConfiguration 允许自动配置(将根据所导入的jar进行自动配置) 2.3 ComponentScan 扫描哪些包或者类所在包的组件 (Repeatable 允许重复配置)