目前(2018.08.05)打开Spring官网(https://spring.io/)首页最醒目的就是spring boot与spring cloud。spring cloud是spring社区近几年主推的微服务框架,而spring boot作为spring cloud的基础就显的尤其重要。我这里介绍Spring Boot也为学习Spring cloud做铺垫。
我们先引用一下Spring Boot官方的概述:
Spring Boot makes it easy to create stand-alone, production-grade Spring-based Applications that you can run. We take an opinionated view of the Spring platform and third-party libraries, so that you can get started with minimum fuss. Most Spring Boot applications need very little Spring configuration.
简而言之:Spring Boot可以利用少量的配置快速搭建一个生产级别的应用程序。
Spring Boot 学习版本: 2.0.4.RELEASE
JDK:8+
Spring Framework :5.0.8.RELEASE+
maven:3.2+
支持嵌入式容器版本:(servlet 3.1)
Tomcat 8.5、Jetty 9.4、Undertow 1.4
兼容所有支持servlet 3.1+的容器
一、CLI
CLI(Command Line Interface)是Spring Boot 提供了一个命令行工具,可以在无需IDE帮助的情况下快速学习、创建、运行Spring Boot程序。可以直击运行Groovy脚本,简化了不必要的样板代码。
1、安装(MAC)
安装指令:(一般会安装最新版本)
brew update
brew tap pivotal/tap
brew install springboot
PS:前提已经安装Brew工具
如果之前已经安装过CLI,但是需要最新版本:brew upgrade springboot
2、运行一个web App
文件FirstSpringBootApp.groovy
@RestController
class FristSpringBootApp {
@RequestMapping("/")
String Hello() {
"Hello World!"
}
}
运行CLI命令:spring run FirstSpringBootApp.groovy
访问地址:http://localhost:8080
如果需要修改端口:spring run
FirstSpringBootApp.
groovy -- --server.port=8989
访问地址:http://localhost:8989
3、打包jar包
spring jar FirstSpringBootApp.jar FirstSpringBootApp.groovy
4、新建项目
spring init --build=maven --java-version=1.8 --dependencies=web --packaging=war firstspringbootspp
其实质也是调用start.spring.io来新建项目
二、start.spring.io快速创建Spring Boot项目
项目结构:
DemoApplication.java启动入库
三、分析pom.xml文件
1、Spring Boot项目都会继承依赖:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
<relativePath/>
</parent>
这样可以看出任何新建的项目都生命为Spring Boot的子项目,这样有利于继承一些合理的默认配置:JDK版本、编码等。还提供了dependency-management,这样就可以省了一些包的版本管理工作。
如添加web相关jar包
只需:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
无需关心版本。
2、创建可执行的jar
<build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build>
该插件可以是打包(mvn package)后的jar变为可执行的jar
java -jar XXX.jar