Spring Boot通过内嵌Tomcat等容器使开发人员可以直接调试,起步依赖和自动配置两大特性大大简化了配置文件,从而使得开发一款基于Spring的可以直接运行的独立生产级应用变得更加简单。现在企业中对Spring Boot的应用也越来越流行,当前最新版本已更新到2.0。SpringBoot2.0学习系列主要参考资料如下:
spring-boot-reference
Spring Boot实战
Java 微服务实践 - Spring Boot 系列
1.创建SpringBoot应用的三种方式
1.1 手动配置
1.1.1 创建项目结构
如下所示,不包含test和resources结构的最简可运行SpringBoot项目结构。
demo
+-- src
| +-- main
| +-- java
| +-- com.example.demo
| +-- DemoApplication.java
+-- pom.xml
1.1.2 编辑pom.xml文件
pom文件需要添加如下的父项目和依赖,其它格式按照通用就行。
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.2.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
1.1.3 编辑SpringBoot启动类
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
1.1.4 运行项目
直接在启动类中右键选择运行即可运行项目,控制台首先打印出Spring字样的Banner以及SpringBoot版本信息,接下来第一行打印该项目对应的进程ID(通过该ID可以用jconsole观察项目运行情况),后面还有内嵌tomcat端口,过滤器,匹配url等信息。

1.2 Spring Initializr
Spring Initializr页面提供了快速创建Spring的方式,如图我们首先选择好构建工具(Maven),开发语言(Java),Spring Boot(2.0.2)版本,然后输入Group ID, Artifact ID后并通过关键词添加相关依赖,最后点击创建项目即可下载Spring Boot项目结构的压缩包,解压后就可以导入到IDE中进行功能开发。

1.3 Idea中创建
在idea界面依次选择File->New->Project打开的面板中选择Spring Initializr,保持默认配置点击Next按钮即可进行1.2中类似的相关配置。


2. Hello World
在启动类上添加@Controller
注解并增加以下内容后启动项目即可通过对应url访问。
@RequestMapping("/")
@ResponseBody
public String hello(){
return "Hello World";
}
@RequestMapping("/rest")
@ResponseBody
public Map<String, Object> rest(){
Map<String, Object> map = new HashMap<String, Object>();
map.put("1", "Hello, Spring Boot!");
map.put("2", 111111111);
return map;
}


3. Actuator
Actuator为Spring Boot应用程序提供了许多web端点,它们以json格式数据的形式反映应用程序运行时的内部状况,在没有jconsole等GUI工具的情况下也能了解程序运行信息。这里对Actuator的使用只作简单介绍,后续会有具体讨论。
3.1 编辑pom.xml
在pom文件中增加actuator依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
3.2 编辑application.properties
因为actuator的端点可能包含有敏感信息,因此对web程序的默认设置并没有暴露它们,这里为了演示效果,直接在application.properties文件中增加management.endpoints.web.exposure.include=*
来暴露所有端点。
3.3 运行访问
右键运行项目后可以看到相对于控制台打印了很以/actuator
作为前缀的url匹配信息,我们在浏览器中可以进行对应的访问,后续再对具体端点进行详细介绍。




网友评论