Spring Boot 的那些事儿

Spring Boot 是个什么东西?官方给出的解释是Spring Boot is designed to get you up and running as quickly as possible, with minimal upfront configuration of Spring. Spring Boot takes an opinionated view of building production-ready applications. 解释下来就是Spring Boot 是为了快速的启动且最小化配置Spring应用而设计的。Spring Boot 采用固化视图来构建生产级别应用。 这是官网首页最显眼的地方摆出的两句话,当然官网推崇Spring Boot 远不止这两句话,下面还来了句更狠的Spring Boot is the starting point for building all Spring-based applications. 这句话有多狠呢?Spring Boot 是都有基于Spring 构建的应用的起点,可见Spring 官方为了推出Spring Boot的决心。

Spring Boot 的特点

下面是官网列出的9个特点,我们逐一了解下

  • Get started in seconds using Spring Initializr
    使用Spring Initializr 几秒的时间就可以启动。我个人的理解是在https://start.spring.io/网址花几秒钟的时间就可以构建一个Spring Boot 项目,刚好这个网页的title就叫Spring Initializr。

    Spring Initializr

  • Build anything: REST API, WebSocket, web, streaming, tasks, and more
    可以用来构建任何东西如: REST API,WebSocket, web, streaming, tasks 这个我们以后探讨。

  • Simplified security
    简化了安全框架,这个比较明确了,需要实践发现如何简化。

  • Rich support for SQL and NoSQL
    良好的支持了SQL和NoSQL

  • Embedded runtime support: Tomcat, Jetty, and Undertow
    嵌入式运行时容器:Tomcat, Jetty, and Undertow,实际上Spring Boot2.0 加入的Web Flux 默认采用的是Netty容器,当然这个后面讨论吧。

  • Developer productivity tools such as LiveReload and Auto Restart
    开发者的生产工具如LiveReload 和 Auto Restart

  • Curated dependencies that just work
    更加精简的依赖

  • Production-ready features such as tracing, metrics, and health status
    提供为生产环境准备的功能如:跟踪、度量和运行状态

  • Works in your favorite IDE: Spring Tool Suite, IntelliJ IDEA, and NetBeans
    可以在你喜欢的IDE上工作如Spring Tool Suite, IntelliJ IDEA, and NetBeans,好吧,我现在用得就是IntelliJ IDEA

说了那么多特点,直接开干就知道了

Spring Initializr直接点generate project 生成项目,存放到本地,解压,目录如下

demo
    │  .gitignore
    │  HELP.md
    │  mvnw
    │  mvnw.cmd
    │  pom.xml
    │  
    ├─.mvn
    │  └─wrapper
    │          maven-wrapper.jar
    │          maven-wrapper.properties
    │          MavenWrapperDownloader.java
    │          
    └─src
        ├─main
        │  ├─java
        │  │  └─com
        │  │      └─example
        │  │          └─demo
        │  │                  DemoApplication.java
        │  │                  
        │  └─resources
        │          application.properties
        │          
        └─test
            └─java
                └─com
                    └─example
                        └─demo
                                DemoApplicationTests.java

windows 下面列出文件目录的指令时tree,将文件和目录一起列出是tree /f ,输出到文件中使用tree /f > list.txt

.gitignore 文件存放的是一些流行的IDE的元信息如STS,IntelliJ IDEA,NetBeans,VS Code
mvnw.cmd 文件配置的是一些maven信息,我们知道Spring Boot 要求使用Maven3.0以上的版本构建,但是有了这个文件后,我们甚至在本机中没有安装Maven也能采Maven来构建项目
pom.xml文件,依赖配置文件,这里我们采用的Spring Boot 版本是org.springframework.boot:spring-boot-starter-parent:2.2.0.M2
DemoApplication.java 启动类

  • 编译启动项目
    进入到pom.xml同级目录使用mvn spring-boot:run 或者mvnw.cmd spring-boot:run启动项目,程序就会自动去下载依赖包和编译,是不是很方便。

由于国内环境下载速度太慢,推荐使用mvn spring-boot:run ,然后我们对本地的maven配置上阿里云镜像 修改settings.xml文件修改
<mirror>
<id>alimaven</id>
<name>aliyun maven</name>
<url>http://maven.aliyun.com/nexus/content/groups/public/</url>
<mirrorOf>central</mirrorOf>
</mirror>

编译启动

这个时候,程序直接退出了,主要原因是没有嵌入式web容器,就是说刚才启动的就是一个普通的Java项目,执行完后就退出了。我们添加依赖org.springframework.boot:spring-boot-starter-web 再启动,这个时候我们就可以去访问http://localhost:8080/ 返回404,当然,我们没有配置信息,至少可以确定,服务器已经启动了。

  • 打包
    刚才已经说过了,我们可以采用mvn spring-boot:run 指令来启动项目,而我们线上环境当然不能那么草率的启动,还是需要jar包或者war包的形式的。我们知道maven的打包指令时mvn package 。那么我们直接试试吧。


    打包

    打包成功,生成了两个文件16.3M的demo-0.0.1-SNAPSHOT.jar和2.75K的demo-0.0.1-SNAPSHOT.jar.original。
    我们再试试打war包,修改pom的packaging为war。执行mvn clean package。如果嫌测试麻烦加上-Dmaven.test.skip=true,打包成功,同样生成demo-0.0.1-SNAPSHOT.war和demo-0.0.1-SNAPSHOT.war.original,这样我们就可以用java -jar 的指令来启动了。

  • 分析包
    解压下demo-0.0.1-SNAPSHOT.jar ,包的目录如下
├─BOOT-INF
│  ├─classes
│  │  └─com
│  │      └─example
│  │          └─demo
│  └─lib
├─META-INF
│  └─maven
│      └─com.example
│          └─demo
└─org
    └─springframework
        └─boot
            └─loader
                ├─archive
                ├─data
                ├─jar
                └─util

我们发现BOOT-INF目录下面有classes目录和lib目录,这个是不是感觉似曾相识?没错,就是WEB-INF目录嘛,当然,web.xml是不存在的。这么看来,classes我们理解成我们写的Java代码编译目录,lib为依赖jar包,这就是个web项目嘛。我们大胆猜测下,Spring Boot其实就是模拟的一个JavaEE项目。
我们再看下jar包的元信息,META-INF/MANIFEST.MF

Manifest-Version: 1.0
Implementation-Title: demo
Implementation-Version: 0.0.1-SNAPSHOT
Built-By: DELL
Implementation-Vendor-Id: com.example
Spring-Boot-Version: 2.2.0.M2
Main-Class: org.springframework.boot.loader.JarLauncher
Start-Class: com.example.demo.DemoApplication
Spring-Boot-Classes: BOOT-INF/classes/
Spring-Boot-Lib: BOOT-INF/lib/
Created-By: Apache Maven 3.5.2
Build-Jdk: 1.8.0_141
Implementation-URL: https://projects.spring.io/spring-boot/#/spring-bo
 ot-starter-parent/demo

我们知道java -jar 指令程序的入口是Main-Class。这个文件中的Main-Class 是JarLauncher,并不是我们的启动类DemoApplication,我们猜想下,使用java JarLauncher 命令是不是也能启动项目。验证了下,发现真的可以启动项目。


image.png

我们假设下jar包里面org目录下为Tomcat容器,那么通过启动Tomcat容器来启动我们的Spring Boot 项目,那么这一切就解释的通了(ps 个人看法)

理解嵌入式Web容器

首先我们将demo项目导入到IDEA中,然后查看下IDEA下的maven依赖如下图:


image.png

我们看到spring-boot-starter-web下面有spring-boot-stater-tomcat的依赖,所以容器默认使用tomcat。如果我们要用Jetty或者Undertow呢?我们以Undertow为例,修改pom.xml文件

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

再次启动项目


image.png

什么鬼,不生效。
根据上面的依赖关系,我们知道spring-boot-starter-web内部有了tomcat的依赖,如果我们不移出的话,依旧会使用tomcat作为容器,那么我们就需要修改spring-boot-satrter-web依赖了

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

重启下项目


image.png

这个时候就使用了Undertow作为web容器了。

从pom.xml为入口再谈编译

首先,Spring 文档中提到了一个Executable Jar的概念,也称为fat jars。就是说将我们的Spring Boot 项目打成一个可执行的jar包,那么如何打包呢?

<build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

我们可以通过spring-boot-maven-plugin插件将我们的项目打成可执行jar包。这就完事了?当然不可能,我们看下这句话If you do not use the parent POM, you need to declare this configuration yourself. 就是说,我们不是以spring-boot-starter-parent 作为parent的话,需要自己声明配置。
那么问题来了,如何不以spring-boot-starter-parent为parent构建Spring Boot 项目呢?

  • 搭建不以spring-boot-starter-parent为parent 的Spring Boot 项目
    为了演示方便,我们修改下启动类DemoApplication.java,将访问http://localhost:8080/ 返回字符串,而不再是报404错误。
@RestController
@SpringBootApplication
public class DemoApplication {
    @RequestMapping("/")
    public String hello(){
        return "hello spring boot";
    }
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

我们再将pom.xml的parent注释掉,然后修改spring-boot-starter-web的依赖,添加版本号

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

我们执行下mvn spring-boot:run 我们发现,启动时成功的,访问下http://localhost:8080/

image.png

返回也没有问题,那么说是不是我们的项目搭建成功了呢?别急,打包试试。篇幅有限,我这里不截图了,打包也是成功的,包是demo-0.0.1-SNAPSHOT.jar,但是我们发现一个问题,这个包只有3K,肯定不是fat jars。
我们翻看下官方文档的 Using Spring Boot without the Parent POM章节,说的是需要添加dependencyManagement依赖,好吧,我们试试。再次maven clean package 发现没什么卵用,还是打的3K的jar包,看来问题不是这个,我们再试试其他办法。(其实dependencyManagement是为了约定spring boot 的版本,我们使用了spring-boot-starter-web:2.1.4.RELEASE 指定好了版本号加不加入影响不大)
我们猜想应该是maven插件的问题了,修改下pom.xml

<build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.1.4.RELEASE</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

repackage描述: create a jar or war file that is auto-executable. It can replace the regular artifact or can be attached to the build lifecycle with a separate classifier. 好吧,这句话就是说创建fat jars,我们加入后,发现打包后和parent效果是一样的。至于为什么使用parent后不需要repackage就能生成fat jars,这个我就不知道了,希望大家帮忙解答下。

之前的依赖发现使用的是2.2.0.M2版本,由于这个是里程碑版本,pom中需要加入一些依赖信息,我们为了方便阅读,之后采取2.1.4.RELEASE版本。刚好,官方的最新文档也是这个版本。

未完,待续

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,015评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,262评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,727评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,986评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,363评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,610评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,871评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,582评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,297评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,551评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,053评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,385评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,035评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,079评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,841评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,648评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,550评论 2 270