第2章 快速開始Hello World
大約20年前奉瘤,程序員們使用“企業(yè)級(jí)Java Bean”(EJB)開發(fā)企業(yè)應(yīng)用亲族,需要配置復(fù)雜的XML种呐。在二十世紀(jì)初期,新興Java技術(shù)——Spring噩死,橫空出世颤难。使用極簡(jiǎn)XML和POJO(普通Java對(duì)象),結(jié)合EJB的替代品(如Hibernate)已维,Spring在企業(yè)級(jí)Java開發(fā)上占據(jù)了絕對(duì)領(lǐng)先地位行嗤。
但是,隨著Spring的不斷發(fā)展垛耳,當(dāng)初的XML配置逐漸變得復(fù)雜龐大栅屏,成了累贅,遭眾多程序員“詬病”堂鲜。后來(lái)栈雳,Spring推出了JavaConfig項(xiàng)目,使用聲明式的注解缔莲,大量減少了顯式的XML配置哥纫。
然而,故事到這里痴奏,并沒有結(jié)束蛀骇。
下面即將進(jìn)入我們的 SpringBoot 之旅。
Boot:引導(dǎo)读拆,啟動(dòng)也擅憔。
本章我們快速開始 Hello World 的體驗(yàn)。
1.1 Spring Boot CLI groovy版Hello World
1.1.1 配置環(huán)境
首先安裝Spring Boot CLI建椰,我們?nèi)ミ@里下載最新版本的壓縮包
http://repo.spring.io/snapshot/org/springframework/boot/spring-boot-cli/
當(dāng)前最新版本是:2.0.0.BUILD-SNAPSHOT 雕欺。
我們把下載好的spring-boot-cli-2.0.0.BUILD-SNAPSHOT-bin.zip 解壓到相應(yīng)的目錄下岛马,然后配置環(huán)境變量:
$vim .bashrc
export SPRING_BOOT_HOME=/Users/jack/soft/spring-2.0.0.BUILD-SNAPSHOT
export PATH=$PATH:$SPRING_BOOT_HOME/bin
在命令行驗(yàn)證spring環(huán)境安裝成功:
$ source .bashrc
$ spring --version
Spring CLI v2.0.0.BUILD-SNAPSHOT
1.1.2 編寫控制器groovy代碼
隨便打開一個(gè)編輯器棉姐,新建文件HelloController.groovy屠列,敲入如下代碼:
@Controller
class HelloController{
@RequestMapping("/hello")
@ResponseBody
String hello(){
return "Hello World!"
}
}
1.1.3 運(yùn)行測(cè)試
然后在命令行執(zhí)行:
$ spring run HelloController.groovy
你將會(huì)在控制臺(tái)看到輸出以下日志
一個(gè)極簡(jiǎn)的Restful Hello World就搞定了。
瀏覽器訪問(wèn):http://localhost:8080/hello(或者curl http://localhost:8080/hello)
你會(huì)看到輸出:
Hello World!
1.2 常規(guī)的Java版的Hello World
1. 創(chuàng)建 SpringBoot Web 項(xiàng)目
我們可以直接在命令行輸入
$ spring init -dweb --build gradle
Using service at https://start.spring.io
Content saved to 'demo.zip'
來(lái)創(chuàng)建一個(gè)模板項(xiàng)目伞矩,也可以到Spring Initializer : https://start.spring.io/ 頁(yè)面進(jìn)行操作笛洛。
為了更加直觀,我們?cè)赟pring Initializer頁(yè)面創(chuàng)建項(xiàng)目示例乃坤。如下圖所示
首先苛让,我們依次選擇 Gradle Project, Java湿诊, SpringBoot 版本是 2.0.0.BUILD-SNAPSHOT 狱杰。
然后,配置項(xiàng)目基本信息
Group :com.easy.springboot
Artifact: chapter1_helloworld
依賴項(xiàng)我們就先只用 Web 厅须。
最后仿畸,點(diǎn)擊 Generate Project , 頁(yè)面會(huì)自動(dòng)生成一個(gè)模板工程 zip 包:chapter1_helloworld.zip 。
2.解壓zip朗和,導(dǎo)入idea中
導(dǎo)入 Gradle 工程错沽,配置 Gradle 環(huán)境,如下圖
等待 IDEA 構(gòu)建完畢眶拉,我們將得到一個(gè)標(biāo)準(zhǔn)的 SpringBoot Application
.
├── build.gradle
├── chapter1_helloworld.iml
├── gradle
│ └── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
└── src
├── main
│ ├── java
│ │ └── com
│ │ └── easy
│ │ └── springboot
│ │ └── chapter1_helloworld
│ │ └── Chapter1HelloworldApplication.java
│ └── resources
│ ├── application.properties
│ ├── static
│ └── templates
└── test
├── java
│ └── com
│ └── easy
│ └── springboot
│ └── chapter1_helloworld
│ └── Chapter1HelloworldApplicationTests.java
└── resources
19 directories, 9 files
3. build.gradle配置文件
我們來(lái)看一下生成的模板工程里面的Gradle配置文件
buildscript {
ext {
springBootVersion = '2.0.0.BUILD-SNAPSHOT'
}
repositories {
mavenCentral()
maven { url "https://repo.spring.io/snapshot" }
maven { url "https://repo.spring.io/milestone" }
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
maven { url "https://repo.spring.io/snapshot" }
maven { url "https://repo.spring.io/milestone" }
}
dependencies {
compile('org.springframework.boot:spring-boot-starter-web')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
我們通過(guò)下面的表格簡(jiǎn)要說(shuō)明如下
配置項(xiàng) | 功能說(shuō)明 |
---|---|
spring-boot-gradle-plugin | 這個(gè)插件在 Gradle中提供了SpringBoot支持千埃,例如打包可執(zhí)行的jar或war,運(yùn)行SpringBoot應(yīng)用程序等功能忆植。它使用spring-boot-dependencies 提供的依賴管理放可。這樣我們?cè)赿ependencies 添加SpringBoot依賴的時(shí)候可以不用指定版本號(hào)。 |
apply plugin: 'org.springframework.boot' | 應(yīng)用spring-boot-gradle-plugin插件 |
compile('org.springframework.boot:spring-boot-starter-web') | Spring 全棧式Web開發(fā)啟動(dòng)器朝刊,包括Tomcat吴侦、spring-webmvc、SpringBoot AutoConfigure 等核心依賴 |
4. SpringBoot 應(yīng)用啟動(dòng)類
我們使用 @SpringBootApplication 注解來(lái)標(biāo)注SpringBoot 應(yīng)用的啟動(dòng)類坞古。
package com.easy.springboot.chapter1_helloworld;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Chapter1HelloworldApplication {
public static void main(String[] args) {
SpringApplication.run(Chapter1HelloworldApplication.class, args);
}
}
同樣的备韧,你將看到控制臺(tái)輸出如下日志:
...
:: Spring Boot :: (v2.0.0.BUILD-SNAPSHOT)
2017-08-01 14:31:43.849 INFO 4987 --- [ main] c.e.s.c.Chapter1HelloworldApplication : Starting Chapter1HelloworldApplication on jacks-MacBook-Air.local with PID 4987
...
2017-08-01 14:31:47.841 INFO 4987 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http)
2017-08-01 14:31:47.846 INFO 4987 --- [ main] c.e.s.c.Chapter1HelloworldApplication : Started Chapter1HelloworldApplication in 5.74 seconds (JVM running for 7.021)
通過(guò)日志,我們可以看到SpringBootApplication大致的啟動(dòng)流程。這個(gè)過(guò)程中掀虎,很大一部分工作是在做SpringBoot 的自動(dòng)配置村斟。
5. @SpringBootApplication注解
@SpringBootApplication注解是 SpringBoot 應(yīng)用的啟動(dòng)類的注解,它包括三個(gè)注解易阳,如下表
注解 | 功能說(shuō)明 |
---|---|
@SpringBootConfiguration | 等同于@Configuration,表示將該類是SpringBoot 應(yīng)用程序入口類 |
@EnableAutoConfiguration | 表示程序啟動(dòng)時(shí)吃粒,啟動(dòng)SpringBoot默認(rèn)的自動(dòng)配置潦俺。自動(dòng)配置類通常根據(jù)類路徑和我們自定義的 bean 來(lái)執(zhí)行相應(yīng)的自動(dòng)配置策略。例如, 如果我們的類路徑上有tomcat-embedded.jar , 那么SpringBoot 就會(huì)嘗試去自動(dòng)配置TomcatServletWebServerFactory Bean事示,或者去配置我們自定義的 ServletWebServerFactory Bean早像。 |
@ComponentScan | 表示程序啟動(dòng)時(shí)自動(dòng)掃描當(dāng)前包及子包下所有類。 |
6. 編寫控制器類HelloWorldController
我們簡(jiǎn)單編寫一個(gè) RestController肖爵,代碼如下
package com.easy.springboot.chapter1_helloworld.controller;
import java.util.Date;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloWorldController {
@RequestMapping("hello")
String hello() {
return "Hello World! " + new Date();
}
}
7. 運(yùn)行測(cè)試
我們?cè)?IDEA 中直接點(diǎn)擊 main 函數(shù)運(yùn)行
可以看到控制臺(tái)輸入如下的日志:
...
:: Spring Boot :: (v2.0.0.BUILD-SNAPSHOT)
2017-08-01 14:57:24.928 INFO 5224 --- [ main] c.e.s.c.Chapter1HelloworldApplication : Starting Chapter1HelloworldApplication on
...
Mapped "{[/hello]}" onto java.lang.String com.example.controller.HelloWorldController.hello()
...
2017-08-01 14:57:28.468 INFO 5224 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http)
2017-08-01 14:57:28.479 INFO 5224 --- [ main] c.e.s.c.Chapter1HelloworldApplication : Started Chapter1HelloworldApplication in 4.128 seconds (JVM running for 4.914)
瀏覽器訪問(wèn):http://localhost:8080/hello
我們將看到如下輸出:
Hello World! Tue Apr 04 23:08:33 CST 2017
另外卢鹦,如果是在命令行運(yùn)行,使用SpringBoot gradle插件的執(zhí)行:
gradle bootRun
如果是使用的 Maven劝堪,那么對(duì)應(yīng)的是SpringBoot maven插件的執(zhí)行:
mvn spring-boot:run
8. 運(yùn)維監(jiān)控
SpringBoot 本身提供了豐富的健康監(jiān)控等運(yùn)維功能冀自,這些功能在 actuator 里。我們?cè)赽uild.gradle的依賴?yán)锩嫣砑右恍衋ctuator的配置
compile('org.springframework.boot:spring-boot-starter-actuator')
為了方便測(cè)試秒啦,我們?cè)赼pplication.properties 添加如下配置
endpoints.metrics.enabled=true
management.security.enabled=false // 去掉安全校驗(yàn)
然后重啟應(yīng)用熬粗,我們可以看到 IDEA 的控制臺(tái)Endpoints 的 Beans Tab界面里面有我們的這個(gè) SpringBoot 應(yīng)用的所有 Bean 的信息列表
Health Tab 界面中我們可以看到服務(wù)器(本機(jī))的磁盤使用信息
在請(qǐng)求映射 Mappings 界面我們可以看到SpringBoot 應(yīng)用提供出來(lái)的所有的 Rest 接口
例如,我們?cè)L問(wèn)http://127.0.0.1:8080/application/health 余境, 可以得到如下輸出
{
"status": "UP",
"diskSpace": {
"status": "UP",
"total": 120108089344,
"free": 1280909312,
"threshold": 10485760
}
}
其他的監(jiān)控 API荐糜,可以類似訪問(wèn),看看輸出的內(nèi)容葛超。關(guān)于spring actuator 監(jiān)控的更多內(nèi)容暴氏,我們將在后面的章節(jié)中介紹。
本章小結(jié)
本章我們通過(guò)兩個(gè)Hello World 實(shí)例绣张,快速體驗(yàn)了 SpringBoot 開發(fā)的過(guò)程答渔。在 SpringBoot 里面我們不再有各種繁雜的 xml 配置,不再有配置侥涵、啟動(dòng)沼撕、運(yùn)行 Tomcat Web 服務(wù)器的一系列繁瑣操作了。
同時(shí)您也一定發(fā)現(xiàn)了:我們的這個(gè) Web 應(yīng)用是怎么啟動(dòng)運(yùn)行的芜飘?
下一章中我們就來(lái)一起學(xué)習(xí)一下 SpringBoot 應(yīng)用的啟動(dòng)過(guò)程和自動(dòng)配置原理务豺。