Spring Boot 概述

Build Anything with Spring Boot:Spring Boot is the starting point for building all Spring-based applications. Spring Boot is designed to get you up and running as quickly as possible, with minimal upfront configuration of Spring.

上面是引自官网的一段话,大概是说: Spring Boot 是所有基于 Spring 开发的项目的起点。Spring Boot 的设计是为了让你尽可能快的跑起来 Spring 应用程序并且尽可能减少你的配置文件。

什么是 Spring Boot

  • 它使用 “习惯优于配置” (项目中存在大量的配置,此外还内置一个习惯性的配置,让你无须手动配置)的理念让你的项目快速运行起来。
  • 它并不是什么新的框架,而是默认配置了很多框架的使用方式,就像 Maven 整合了所有的 jar 包一样,Spring Boot 整合了所有框架

使用 Spring Boot 有什么好处

回顾我们之前的 SSM 项目,搭建过程还是比较繁琐的,需要:

  • 1)配置 web.xml,加载 spring 和 spring mvc
  • 2)配置数据库连接、配置日志文件
  • 3)配置家在配置文件的读取,开启注解
  • 4)配置mapper文件
  • .....

而使用 Spring Boot 来开发项目则只需要非常少的几个配置就可以搭建起来一个 Web 项目,并且利用 IDEA 可以自动生成生成

  • 划重点:简单、快速、方便地搭建项目;对主流开发框架的无配置集成;极大提高了开发、部署效率。

Spring Boot HelloWorld

导入依赖spring boot相关的依赖

<?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"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>cn.chenhao</groupId><artifactId>springboot</artifactId><version>1.0.0-SNAPSHOT</version><packaging>jar</packaging><name>springboot</name><description>Demo project for Spring Boot</description><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.0.1.RELEASE</version><relativePath/></parent><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build>
</project>

编写主程序

/*** @SpringBootApplication来标注一个主程序类,说明这是一个SpringBoot应用*/
@SpringBootApplication
public class HelloWorldMainApplication {public static void main(String[] args) {//Spring应用启动SpringApplication.run(HelloWorldMainApplication.class, args);}
}

编写Controller、Service

@RestController
public class HelloController {@RequestMapping("/hello")public String hello(){return "Hello world";}
}

运行主程序测试

使用maven打包命令将其打包成jar包后,直接使用命令:

java -jar xxx.jar

Hello World探究

POM文件

父项目

<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.0.1.RELEASE</version><relativePath/>
</parent>

其父项目是

<parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-dependencies</artifactId><version>2.0.1.RELEASE</version><relativePath>../../spring-boot-dependencies</relativePath>
</parent>

该父项目是真正管理Spring Boot应用里面的所有依赖的版本:Spring Boot的版本仲裁中心,所以以后导入的依赖默认是不需要版本号。如下:

还有很多版本号没有截图出来

启动器

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency>

spring-boot-starter : spring boot场景启动器;帮助导入web模块正常运行所依赖的组件;

​ Spring Boot将所有的功能场景抽取出来,做成一个个的starter(启动器),只需要在项目中引入这些starter,那么相关的场景的所有依赖都会导入进项目中。要用什么功能就导入什么场景的启动器。

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<dependency><groupId>org.springframework</groupId><artifactId>spring-web</artifactId>
</dependency>
<dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId>
</dependency>

添加了 spring-boot-starter-web 依赖,会自动添加 Tomcat 和 Spring MVC 的依赖

spring-boot-starter-web中又引入了spring-boot-starter-tomcat

主程序类(主入口类)

@SpringBootApplication
public class HelloWorldMainApplication {public static void main(String[] args) {//Spring应用启动SpringApplication.run(HelloWorldMainApplication.class, args);}
}

@SpringBootApplication

  • Spring Boot应用标注在某个类上,说明这个类是SpringBoot的主配置类,SpringBoot就应该运行这个类的main方法来启动SpringBoot应用。

注解定义如下:

@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {@Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {}

@SpringBootConfiguration

  • Spring Boot的配置类
  • 标注在某个类上,表示这是一个Spring Boot的配置类

注解定义如下:

@Configuration
public @interface SpringBootConfiguration {}

其实就是一个Configuration配置类,意思是HelloWorldMainApplication最终会被注册到Spring容器中

@EnableAutoConfiguration

  • 开启自动配置功能
  • 以前使用Spring需要配置的信息,Spring Boot帮助自动配置;
  • @EnableAutoConfiguration通知SpringBoot开启自动配置功能,这样自动配置才能生效。

注解定义如下:

@AutoConfigurationPackage
@Import(EnableAutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {}

@AutoConfigurationPackage

  • 自动配置包注解
@Import(AutoConfigurationPackages.Registrar.class)
public @interface AutoConfigurationPackage {}

@Import(AutoConfigurationPackages.Registrar.class):默认将主配置类(@SpringBootApplication)所在的包及其子包里面的所有组件扫描到Spring容器中。如下

@Order(Ordered.HIGHEST_PRECEDENCE)
static class Registrar implements ImportBeanDefinitionRegistrar, DeterminableImports {@Overridepublic void registerBeanDefinitions(AnnotationMetadata metadata,BeanDefinitionRegistry registry) {//默认将会扫描@SpringBootApplication标注的主配置类所在的包及其子包下所有组件register(registry, new PackageImport(metadata).getPackageName());}@Overridepublic Set<Object> determineImports(AnnotationMetadata metadata) {return Collections.<Object>singleton(new PackageImport(metadata));}
}

@Import(EnableAutoConfigurationImportSelector.class)

EnableAutoConfigurationImportSelector: 导入哪些组件的选择器,将所有需要导入的组件以全类名的方式返回,这些组件就会被添加到容器中。

//EnableAutoConfigurationImportSelector的父类:AutoConfigurationImportSelector
@Override
public String[] selectImports(AnnotationMetadata annotationMetadata) {if (!isEnabled(annotationMetadata)) {return NO_IMPORTS;}try {AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader.loadMetadata(this.beanClassLoader);AnnotationAttributes attributes = getAttributes(annotationMetadata);List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes);configurations = removeDuplicates(configurations);configurations = sort(configurations, autoConfigurationMetadata);Set<String> exclusions = getExclusions(annotationMetadata, attributes);checkExcludedClasses(configurations, exclusions);configurations.removeAll(exclusions);configurations = filter(configurations, autoConfigurationMetadata);fireAutoConfigurationImportEvents(configurations, exclusions);return configurations.toArray(new String[configurations.size()]);}catch (IOException ex) {throw new IllegalStateException(ex);}
}

我们主要看第11行List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes);会给容器中注入众多的自动配置类(xxxAutoConfiguration),就是给容器中导入这个场景需要的所有组件,并配置好这些组件。我们跟进去看看

protected List<String> getCandidateConfigurations(AnnotationMetadata metadata,AnnotationAttributes attributes) {List<String> configurations = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader());//...return configurations;
}protected Class<?> getSpringFactoriesLoaderFactoryClass() {return EnableAutoConfiguration.class;
}public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";public static List<String> loadFactoryNames(Class<?> factoryClass, ClassLoader classLoader) {String factoryClassName = factoryClass.getName();try {//从类路径的META-INF/spring.factories中加载所有默认的自动配置类Enumeration<URL> urls = (classLoader != null ? classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));List<String> result = new ArrayList<String>();while (urls.hasMoreElements()) {URL url = urls.nextElement();Properties properties = PropertiesLoaderUtils.loadProperties(new UrlResource(url));//获取EnableAutoConfiguration指定的所有值,也就是EnableAutoConfiguration.class的值String factoryClassNames = properties.getProperty(factoryClassName);result.addAll(Arrays.asList(StringUtils.commaDelimitedListToStringArray(factoryClassNames)));}return result;}catch (IOException ex) {throw new IllegalArgumentException("Unable to load [" + factoryClass.getName() + "] factories from location [" + FACTORIES_RESOURCE_LOCATION + "]", ex);}
}

SpringBoot启动的时候从类路径下的 META-INF/spring.factories中获取EnableAutoConfiguration指定的值,并将这些值作为自动配置类导入到容器中,自动配置类就会生效,最后完成自动配置工作。EnableAutoConfiguration默认在spring-boot-autoconfigure这个包中,如下图

最终有96个自动配置类被加载并注册进Spring容器中

J2EE的整体整合解决方案和自动配置都在spring-boot-autoconfigure-xxx.jar中。在这些自动配置类中会通过@ConditionalOnClass等条件注解判断是否导入了某些依赖包,从而通过@Bean注册相应的对象进行自动配置。后面我们会有单独文章讲自动配置的内容


作者:chen_hao
链接:https://www.cnblogs.com/java-chen-hao/p/11829056.html
来源:博客园

springboot web项目_SpringBoot 源码解析 (一):SpringBoot核心原理入门相关推荐

  1. SpringBoot物流管理项目(源码下载)

    SpringBoot物流管理项目(源码下载) https://mp.weixin.qq.com/s?__biz=Mzg3NjI4OTg1Mw==&mid=100016342&idx=1 ...

  2. php 框架源码分析,Laravel框架源码解析之模型Model原理与用法解析

    本文实例讲述了Laravel框架源码解析之模型Model原理与用法.分享给大家供大家参考,具体如下: 前言 提前预祝猿人们国庆快乐,吃好.喝好.玩好,我会在电视上看着你们. 根据单一责任开发原则来讲, ...

  3. maven 公共模块依赖_「spring-boot 源码解析」spring-boot 依赖管理

    问题 maven 工程,依赖管理是非常基本又非常重要的功能,现在的工程越来越庞大,依赖越来越多,各种二方包.三方包太多太多,依赖冲突处理起来真是让人头疼,经常需要涉及到多个地方需要调整. 微信公众号: ...

  4. Spring AOP源码解析——AOP动态代理原理和实现方式

    2019独角兽企业重金招聘Python工程师标准>>> Spring介绍 Spring(http://spring.io/)是一个轻量级的Java 开发框架,同时也是轻量级的IoC和 ...

  5. springboot(二)自动化配置源码解析

    @EnableAutoConfiguration 是开启自动配置的注解,在创建的 SpringBoot 项目中并不能直接看到此注解,它是由组合注解@SpringBootApplication 引入的. ...

  6. SpringBoot文件上传源码解析

    一.SpringMVC文件上传源码分析前言(这部分我觉得原作者写的很好) 该如何研究SpringMVC的文件上传的源码呢? 研究源码并不是仅仅知道程序是怎样运行的,而应该从宏观的角度.不同的立场去看待 ...

  7. SpringBoot rest映射及源码解析

    一.rest使用与原理 • @xxxMapping: • Rest风格支持(使用HTTP请求方式动词来表示对资源的操作) • 以前:/getUser 获取用户 /deleteUser 删除用户 /ed ...

  8. 宠物领养管理系统|宠物寄养管理系统JAVA|JSP|SSM|Springboot|web计算机毕业设计源码

    1.开发语言:JAVA/JSP(SSH.SSM.Springboot).Aspnet.PHP.python.安卓                         APP.微信小程序 2.含有资料:毕业 ...

  9. (转)spring源码解析,spring工作原理

    转自:https://www.ibm.com/developerworks/cn/java/j-lo-spring-principle/ Spring 的骨骼架构 Spring 总共有十几个组件,但是 ...

  10. log4j 源码解析_Log4j源码解析--框架流程+核心解析

    OK,现在我们来研究Log4j的源码: 这篇博客有参照上善若水的博客,原文出处:http://www.blogjava.net/DLevin/archive/2012/06/28/381667.htm ...

最新文章

  1. Oracle10g安装中遇到的错误及解决办法
  2. 矩阵消除游戏--牛客练习赛58
  3. html监听页面关闭事件,JS针对浏览器窗口关闭事件的监听方法集锦
  4. Java对象容器——Hash表/散列表
  5. SQL Server 预读和物理读 的区别
  6. mysql5.7 on windows
  7. springboot undertow替换tomcat方式
  8. HTML5笔记:跨域通讯、多线程、本地存储和多图片上传技术
  9. asp.net中实现登陆的时候用SSL
  10. 设置 无线网 连接到服务器未响应,设置无线路由器显示服务器未响应
  11. Ardunio开发实例-MMA8653FC 10位加速度计
  12. 计算机基础 MBR主引导记录
  13. php 图片上载 wordpress,WordPress 使用 Jcorp上传并裁剪图片作为自定义头像 —— PHP 后台部分...
  14. [统计学笔记] (八)分类数据分析
  15. 李宏毅《Deep Learning》学习笔记 - transformer
  16. 搭建家庭影音媒体中心 --公网远程连接Jellyfin流媒体服务器
  17. 测验1: Python快速入门 (第2周)
  18. Android事件分发机制:ViewRootImpl篇(前传)
  19. 【计算机毕业设计】基于微信小程序的师生答疑平台的设计与实现
  20. phpwind携手区域网站深度合作 欲建中小网站电子商务数据平台

热门文章

  1. 54.Linux/Unix 系统编程手册(下) -- POSIX 共享内存
  2. 11.卷2(进程间通信)--- System V 信号量
  3. 40. MySQL的权限与安全
  4. 2. 配置Xdebug
  5. 性能测试场景设计之用户启停设置
  6. centos7磁盘备份和还原
  7. SpringMvc上传文件遇到重复读取InputStream的问题
  8. 浅谈java 之 Map
  9. Wijmo 5 与Breeze 的组合,及与METRONIC 的集成
  10. iOS中Lua脚本应用笔记一:脚本概念相关