Spring Boot 2.0 入门指南
0x01 什么是Spring Boot?
Spring Boot是用来简化Spring应用初始搭建以及开发过程的全新框架,被认为是Spring MVC的“接班人”,和微服务紧密联系在一起。
0x02 为什么学习Spring Boot?
微服务是如今各大企业都开始火热使用的技术,而Spring Boot 是学习Spring Cloud的基础
0x03 Spring Boot 有什么特点?
1.化繁为简
2. 备受关注,是下一代框架
3. 微服务的入门级微框架
0x04 Spring Boot 的目标?
为所有的Spring开发提供一个更快速、更广泛的入门体验
但是当需求和默认配置偏离时,请尽快放弃使用Spring Boot.
提供一系列的非功能性的特点,是大类项目(如嵌入式服务器,安全,标准,健康检查,和外部配置)。
绝对不生成代码,也不需要XML配置。
0x05 准备环境
系统要求
Spring Boot 2.0.0.BUILD-SNAPSHOT 需要JDK1.8 以上和Spring Framework 5.0.2.Release 以上版本
构建支持Maven3.2+ 和Gradle4
Servlet 容器

Tips: 也可以将Spring Boot 应用程序部署到任何兼容Servlet 3容器中。
技能要求
熟悉Maven 项目构建
熟悉Spring 注解
熟悉RESful API的理念
IDE
本节课程使用Intellij Idea 作为开发工具
0x06 创建我们的第一个应用程序
接下来我们将会创建一个带有Spring-Data-JPA功能的Spring-Boot Sample。
1. 打开我们的Intellij IDEA,选择 ‘Create New Project’

2. 选择Spring Initializr来帮助我们快速创建Spring Boot 程序,JDK 最低1.8,Intializr Service URL保持默认。

3. 输入以下项目配置信息

4. 勾选 Web模块

5.SQL 模块分类中勾选 MySQL 和JPA 模块

6. 接下来工程信息一切保持默认即可

7. 修改POM.xml
<?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>com.xingyun</groupId>
<artifactId>spring-boot-with-data-jpa-sample</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <name>spring-boot-with-data-jpa-sample</name>
<description>Demo project for Spring Boot</description> <parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency> <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> </project>
8.默认的系统配置文件是application.properties
# 配置应用程序的端口
server.port=8080
#配置应用程序的上下文
server.servlet.context-path=/
Tips: 我们可以通过这种文件来配置web项目的全局上下文路径和端口号等,但是这里我们需要注释或者删除掉他们,因为我们有一个更好的方式来实现他们。
9. 配置我们的yml文件
总的配置文件,我们可以通过active:dev|prod 激活我们的开发环境配置或者生产环境配置
application.yml
spring:
profiles:
active: dev
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/dbgirl
username: root
password:
jpa:
hibernate:
ddl-auto: create
dialect: MySQLDialect
show-sql: true
Spring 2.0 更新变动

开发环境配置文件
application-dev.yml
server:
port: 8081
servlet:
context-path: /
cupSize: B
age: 18
content: "cupSize=${cupSize},age=${age}"
book:
name: 第二行代码
price: 66.00
type: 安卓
生产环境配置文件
application-prod.yml
server:
port: 8086
servlet:
context-path: /
cupSize: B
age: 18
content: "cupSize=${cupSize},age=${age}"
book:
name: 第二行代码
price: 66.00
type: 安卓
10. 代码结构图如图所示

10.1 代码中获取配置文件中的属性
我们可以读取刚才开发环境下配置文件中的定义的常量属性通过下面的方法
@Value("${cupSize}")
private String cupSize;
@Value("${age}")
private Integer age;
@Value("${content}")
private String content;
@RequestMapping(value = "/girl",method = RequestMethod.GET)
public String configurationString(){
return cupSize+"-----------------"+age+"-------------"+content;
}
当然如果要配置的常量比较多的时候我们就不能使用上面的方法了,但是我们也有更好的方式实现
10.2 代码中获取配置文件中的属性实体
首先创建实体类 BookProperties.java
package com.xingyun.springbootwithdatajpasample.model; import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component; @Component
@ConfigurationProperties(prefix = "book")
public class BookProperties { private String name; private Double price; private String type; public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public Double getPrice() {
return price;
} public void setPrice(Double price) {
this.price = price;
} public String getType() {
return type;
} public void setType(String type) {
this.type = type;
}
}
Tips: 注意此文件中用到的两个注解不可省略必须有才行
调用方法如下所示:
@Autowired
private BookProperties bookProperties; @RequestMapping(value = "/book",method = RequestMethod.GET)
public String bookMethod(){
return "---------------------"+bookProperties.getName()+bookProperties.getPrice()+bookProperties.getType();
}
10.3 默认的单个URL映射
@RequestMapping(value = "/",method = RequestMethod.GET)
public String home(){
return "Hello Home Page";
} @RequestMapping(value = "/hello",method = RequestMethod.GET)
public String say(){
return "Hello Spring Boot";
}
10.4 多个URL映射
@RequestMapping(value = {"/api","/API"},method = RequestMethod.GET)
public String api(){
return "Hello API";
}
10.5 Post 方式访问
@RequestMapping(value = "/post",method = RequestMethod.POST)
public String PostMethod(){
return "Hello Post Page";
}
10.6 传统风格的URL
@RequestMapping(value = "/url/b",method = RequestMethod.GET)
public String urlWithQuestion(@RequestParam(value = "id",required = false,defaultValue = "0") Integer uid){
return "Hello URL -----/url/b?id=***------id="+uid;
}
访问请求:
http://127.0.0.1:8081/url/b?id=18
10.7 Restful 风格的URL
@RequestMapping(value = "/url/a/{id}",method = RequestMethod.GET)
public String urlWithParams(@PathVariable("id") Integer uid){
return "Hello URL -----url/a/***------id="+uid;
}
访问请求:
http://127.0.0.1:8081/url/a/18
10.8 组合注解
上面我们应该已经发现,既要配置GET/POST又要配置映射路径很麻烦,因此我们今后可以用组合注解
@GetMapping(value = "/url/c")
public String urlWithQuestion2(@RequestParam(value = "id",required = false,defaultValue = "0") Integer uid){
return "Hello URL -----/url/c?id=***------id="+uid;
}
访问请求:
http://127.0.0.1:8081/url/c?id=18
10.9 @JsonFormat Date注解
关于JsonFormat 时间如果希望格式化时间为12小时制的,则使用hh:mm:ss 如果希望格式化时间为24小时制的,则使用HH:mm:ss
@JsonFormat(pattern = "yyyy-mm-dd HH:ss:mm",locale = "zh",timezone = "GMT+8")//2018-40-07 16:24:40
Date publishedTime;//发表时间
@JsonFormat(pattern = "yyyy-mm-dd hh:ss:mm a",locale = "zh",timezone = "GMT+8")//2018-40-07 04:24:40 下午
Date updatedTime;//修改时间
10.10 使用Spring-Data-JPA 组件结合MySQL实现数据库的增删改查操作
首先我们需要定义一个实体类Girl.java
package com.xingyun.springbootwithdatajpasample.model; import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id; @Entity
public class Girl { @Id
@GeneratedValue
private Integer id;
private String girlName;
private Integer girlAge; public Girl() {
} public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getGirlName() {
return girlName;
} public void setGirlName(String girlName) {
this.girlName = girlName;
} public Integer getGirlAge() {
return girlAge;
} public void setGirlAge(Integer girlAge) {
this.girlAge = girlAge;
}
}
Tips: 特别注意,几个注解不能少,引入的包路径千万别导错包了,不然会报错。
然后需要创建一个接口类 GirlRepository.java
package com.xingyun.springbootwithdatajpasample.mmInterface; import com.xingyun.springbootwithdatajpasample.model.Girl;
import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; public interface GirlRepository extends JpaRepository<Girl,Integer>{ //自定义接口
public List<Girl> findByGirlAge(Integer girlAge);
}
Tips: 我们需要继承JpaRepository<Girl,Integer>, 这样Spring-Data-JPA就会帮我们实现基本的增删改查。
当然这默认的增删改查无法满足我们的实际业务需求,所以我们也可以在这里扩展我们实现的接口。
增删改查调用代码如下所示:
package com.xingyun.springbootwithdatajpasample.controller; import com.xingyun.springbootwithdatajpasample.mmInterface.GirlRepository;
import com.xingyun.springbootwithdatajpasample.model.Girl;
import com.xingyun.springbootwithdatajpasample.service.GirlService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*; import java.util.List;
import java.util.Optional; @RestController
public class GirlController { @Autowired
private GirlRepository girlRepository; @Autowired
private GirlService girlService; /**
* 查询所有女生列表
* @Return
* */
@GetMapping("/girls")
public List<Girl> getGirlList(){
return girlRepository.findAll();
} /**
* 添加一个女生
* */
@PostMapping("/girls")
public Girl girlAdd(@RequestParam("girlName") String girlName,@RequestParam("girlAge") Integer girlAge){ Girl girl=new Girl();
girl.setGirlName(girlName);
girl.setGirlAge(girlAge);
girlRepository.save(girl);
return girl;
} /**
* 添加两个女生
* */
@GetMapping("/girls/two")
public String girlAddTwo(){
girlService.insertTwo();
return "success";
} /**
* 通过Id查询一个女生
* */
@GetMapping("/girls/{id}")
public Optional<Girl> girlFindById(@PathVariable("id") Integer uid){
return girlRepository.findById(uid);
}
/**
* 通过年龄查询一个女生
* */
@GetMapping("/girls/age/{girlAge}")
public List<Girl> girlFindByAge(@PathVariable("girlAge") Integer age){
return girlRepository.findByGirlAge(age);
} /**
* 修改一个女生
*/
@PostMapping(value="/girls/{id}")
public Girl girlUpdate(@PathVariable("id") Integer uid,@RequestParam("girlName") String girlName,@RequestParam("girlAge") Integer girlAge){
Girl girl=new Girl();
girl.setId(uid);
girl.setGirlName(girlName);
girl.setGirlAge(girlAge);
return girlRepository.save(girl);
} /**
* 删除一个Id
* */
@DeleteMapping(value = "/girls/{id}")
public void girlDelete(@PathVariable("id") Integer uid){
girlRepository.deleteById(uid);
}
}
Tips: 这里要注意的一点是我这个版本使用的是 Spring-Boot 2.0.0.RELEASE 版本,更新后有个方法做了修改。
public List<Girl> girlFindById(@PathVariable("id") Integer uid){
return girlRepository.findById(uid);
}
这个返回集合不再有效,需要改成下面这种:
@GetMapping("/girls/{id}")
public Optional<Girl> girlFindById(@PathVariable("id") Integer uid){
return girlRepository.findById(uid);
}
11. 可能出现的问题
在初次学习时候可能会出现一些常见的异常,可以移步去我的CSDN博客看这篇文章
细数Spring Boot 中容易中招的那些坑
https://blog.csdn.net/hadues/article/details/79334355
@ConfigurationProperties(prefix = "xxx")的值取出为空
https://blog.csdn.net/hadues/article/details/79123645
真正解决方案:java.lang.ClassNotFoundException: javax.xml.bind.JAXBException
https://blog.csdn.net/hadues/article/details/79188793
12. 学习源码下载
使用前请在本地创建MySQL数据库dbgirl
dbgirl.sql
-- phpMyAdmin SQL Dump
-- version 4.7.4
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: 2018-03-28 03:43:53
-- 服务器版本: 10.1.30-MariaDB
-- PHP Version: 7.2.1 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */; --
-- Database: `dbgirl`
-- -- -------------------------------------------------------- --
-- 表的结构 `girl`
-- CREATE TABLE `girl` (
`id` int(11) NOT NULL,
`girl_age` int(11) DEFAULT NULL,
`girl_name` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; --
-- Indexes for dumped tables
-- --
-- Indexes for table `girl`
--
ALTER TABLE `girl`
ADD PRIMARY KEY (`id`); --
-- 在导出的表使用AUTO_INCREMENT
-- --
-- 使用表AUTO_INCREMENT `girl`
--
ALTER TABLE `girl`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
调用参考readme.txt
使用前需启动My SQL数据库
MySQL default username:root default password: 1. http://127.0.0.1:8081/ 2. http://127.0.0.1:8081/hello 3. http://127.0.0.1:8081/girl 4.http://127.0.0.1:8081/book 5.http://127.0.0.1:8081/api
http://127.0.0.1:8081/API
Tips: Get 请求,多映射
7.http://127.0.0.1:8081/api
Tips:Post 请求 8.http://127.0.0.1:8081/url/a/18 9.http://127.0.0.1:8081/url/b?id=18 10.http://127.0.0.1:8081/url/c?id=18 Tips:组合注解 @GetMapping(value = "/url/c") 11.http://127.0.0.1:8081/girls/ Tips:Get 获取所有女生列表 12. http://127.0.0.1:8081/girls/ Tips: Post girlName girlAge 添加一个女生 13.http://127.0.0.1:8081/girls/two Tips:添加两个女生 14.根据Id 查询女生
http://127.0.0.1:8081/girls/1 15.根据年龄查询女生
http://127.0.0.1:8081/girls/age/16 16. http://127.0.0.1:8081/girls/1 Tips:girlName girlAge Post 根据Id修改一个女生 17.http://127.0.0.1:8081/girls/1 Tips:Delete 请求根据id删除一个女生 创建数据库bean时候切记不要导错包名 import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
推荐学习免费视频教程地址:http://www.imooc.com/learn/767
Spring Boot 2.0 入门指南的更多相关文章
- Spring Boot 2.0 升级指南
Spring Boot 2.0 升级指南 前言 Spring Boot已经发布2.0有5个月多,多了很多新特性,一些坑也慢慢被填上,最近有空,就把项目中Spring Boot 版本做了升级,顺便整理下 ...
- Spring Boot 2.0 迁移指南
:Spring Boot 2.0 项目源码结构预览
关注我 转载请务必注明原创地址为:http://www.54tianzhisheng.cn/2018/04/15/springboot2_code/ 项目结构 结构分析: Spring-boot-pr ...
- Spring Boot 2.0系列文章(七):SpringApplication 深入探索
关注我 转载请务必注明原创地址为:http://www.54tianzhisheng.cn/2018/04/30/springboot_SpringApplication/ 前言 在 Spring B ...
- 学习Spring Boot:(二十七)Spring Boot 2.0 中使用 Actuator
前言 主要是完成微服务的监控,完成监控治理.可以查看微服务间的数据处理和调用,当它们之间出现了异常,就可以快速定位到出现问题的地方. springboot - version: 2.0 正文 依赖 m ...
- Spring Boot 2.0 的快速入门(图文教程)
摘要: 原创出处 https://www.bysocket.com 「公众号:泥瓦匠BYSocket 」欢迎关注和转载,保留摘要,谢谢! Spring Boot 2.0 的快速入门(图文教程) 大家都 ...
- 【SFA官方翻译】使用 Kubernetes、Spring Boot 2.0 和 Docker 的微服务快速指南
[SFA官方翻译]使用 Kubernetes.Spring Boot 2.0 和 Docker 的微服务快速指南 原创: Darren Luo SpringForAll社区 今天 原文链接:https ...
- Spring Boot 2.0 热部署指南
Spring Boot 2.0 支持热部署,实现方法很简单 Spring Boot 2.0 有几种热重载的选项. 推荐的方法是使用spring-boot-devtools 因为它提供了额外的开发时间功 ...
- Spring Boot 2.0 + zipkin 分布式跟踪系统快速入门
原文:https://www.jianshu.com/p/9bfe103418e2 注意 Spring Boot 2.0之后,使用EnableZipkinServer创建自定义的zipkin服务器已经 ...
随机推荐
- POJ3237 Tree 树链剖分 线段树
欢迎访问~原文出处——博客园-zhouzhendong 去博客园看该题解 题目传送门 - POJ3237 题意概括 Description 给你由N个结点组成的树.树的节点被编号为1到N,边被编号为1 ...
- Python3 - 基础知识、基本了解
一.Python到底是什么? (抄自 金角大王) 1. Python是一门解释型语言? 我初学Python时,听到的关于Python的第一句话就是,Python是一门解释性语言,我就这样一直相信下去, ...
- Python爬虫之正则表达式的使用(三)
正则表达式的使用 re.match(pattern,string,flags=0) re.match尝试从字符串的起始位置匹配一个模式,如果不是起始位置匹配成功的话,match()就返回none 参数 ...
- Autodesk系列软件下载
摘要: 写在前面:下载后如有需要压缩密码的请先使用压缩软件(如:2345好压)打开压缩包,在压缩包的注释或者文本信息中会给出压缩密码!如若没有请私信! 1.3ds Max软件(64位) Autodes ...
- sublime使用技巧之添加到右键菜单、集成VI
熟悉开发工具,减少多余的操作流程有助于提高开发效率,而Sublime Text 2是sublime产品的经典版本,因此本文基于Sublime Text 2讲解sublime的使用技巧. VI的主要作用 ...
- Python学习——collections系列
一 ,计数器(counter) Counter是对字典类型的补充,用于追踪值得出现次数 ps:具备字典的所有功能 + 自己的功能 例: >>> from collections im ...
- BZOJ.2453.维护队列([模板]带修改莫队)
题目链接 带修改莫队: 普通莫队的扩展,依旧从[l,r,t]怎么转移到[l+1,r,t],[l,r+1,t],[l,r,t+1]去考虑 对于当前所在的区间维护一个vis[l~r]=1,在修改值时根据是 ...
- php在windows下发送邮件实现
一.使用PHP内置的mail()函数 看了一下手册,就直接开始写代码了,如下: <?php $to = "test@126.com"; //收件人 $subject = &q ...
- 学JAVA二十一天,自定义数组
今天就说一下自定义数组,至于要怎么用,我也不知道,反正逼格挺高的. 闲话不多说,开始: 首先,自定义数组首先要创建一个类,用来做自定义数组的类型. public class User{ private ...
- 常用伪元素及content属性值的使用
1.常用伪元素有 after.before,使用方法,如下 a:after{ display:block; content:''; } 2. content: "/\00a0";/ ...