找回密码
 注册【用户名必须为中文字符】

QQ登录

只需一步,快速开始

Spring Boot 2.0 入门指南

admin 回复:0 | 查看:4418 | 发表于 2020-2-26 23:30:21 |阅读模式 |复制链接
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
[url=][/url]
<?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>[url=][/url]

8.默认的系统配置文件是application.properties
# 配置应用程序的端口
server.port=8080
#配置应用程序的上下文
server.servlet.context-path=/

Tips: 我们可以通过这种文件来配置web项目的全局上下文路径和端口号等,但是这里我们需要注释或者删除掉他们,因为我们有一个更好的方式来实现他们。
9. 配置我们的yml文件
总的配置文件,我们可以通过active:dev|prod 激活我们的开发环境配置或者生产环境配置
application.yml
[url=][/url]
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[url=][/url]

Spring 2.0 更新变动
开发环境配置文件
application-dev.yml
[url=][/url]
server:  port: 8081  servlet:    context-path: /cupSize: Bage: 18content: "cupSize=${cupSize},age=${age}"book: name: 第二行代码 price: 66.00 type: 安卓[url=][/url]

生产环境配置文件
application-prod.yml
[url=][/url]
server:  port: 8086  servlet:    context-path: /cupSize: Bage: 18content: "cupSize=${cupSize},age=${age}"book: name: 第二行代码 price: 66.00 type: 安卓[url=][/url]

10. 代码结构图如图所示
10.1 代码中获取配置文件中的属性
我们可以读取刚才开发环境下配置文件中的定义的常量属性通过下面的方法
[url=][/url]
    @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;    }[url=][/url]

当然如果要配置的常量比较多的时候我们就不能使用上面的方法了,但是我们也有更好的方式实现10.2 代码中获取配置文件中的属性实体
首先创建实体类 BookProperties.java
[url=][/url]
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;    }}[url=][/url]

Tips: 注意此文件中用到的两个注解不可省略必须有才行
调用方法如下所示:
[url=][/url]
@Autowired    private BookProperties bookProperties;    @RequestMapping(value = "/book",method = RequestMethod.GET)    public String bookMethod(){        return "---------------------"+bookProperties.getName()+bookProperties.getPrice()+bookProperties.getType();    }[url=][/url]

10.3 默认的单个URL映射[url=][/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";    }[url=][/url]

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
[url=][/url]
package com.xingyun.springbootwithdatajpasample.model;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;@Entitypublic 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;    }}[url=][/url]

Tips: 特别注意,几个注解不能少,引入的包路径千万别导错包了,不然会报错。
然后需要创建一个接口类 GirlRepository.java
[url=][/url]
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);}[url=][/url]

Tips: 我们需要继承JpaRepository<Girl,Integer>, 这样Spring-Data-JPA就会帮我们实现基本的增删改查。
当然这默认的增删改查无法满足我们的实际业务需求,所以我们也可以在这里扩展我们实现的接口。
增删改查调用代码如下所示:
[url=][/url]
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;@RestControllerpublic 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);    }}[url=][/url]

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 中容易中招的那些坑  
@ConfigurationProperties(prefix = "xxx")的值取出为空
真正解决方案:java.lang.ClassNotFoundException: javax.xml.bind.JAXBException  
12. 学习源码下载
使用前请在本地创建MySQL数据库dbgirl
dbgirl.sql
[url=][/url]
-- 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.1SET 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 */;[url=][/url]

调用参考readme.txt
[url=][/url]
使用前需启动My SQL数据库MySQLdefault username:rootdefault password:1. http://127.0.0.1:8081/2. http://127.0.0.1:8081/hello3. http://127.0.0.1:8081/girl4.http://127.0.0.1:8081/book5.http://127.0.0.1:8081/api  http://127.0.0.1:8081/API  Tips: Get 请求,多映射7.http://127.0.0.1:8081/apiTipsost 请求8.http://127.0.0.1:8081/url/a/189.http://127.0.0.1:8081/url/b?id=1810.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  Tipselete 请求根据id删除一个女生  创建数据库bean时候切记不要导错包名  import javax.persistence.Entity;  import javax.persistence.GeneratedValue;  import javax.persistence.Id;[url=][/url]

推荐学习免费视频教程地址:http://www.imooc.com/learn/767

回复

使用道具 举报

本版积分规则

联系我们

对话产生契机,讨论收获惊喜, 只为成就无限创举

江苏省南通市通州区太湖路88号

欢迎来这里一起喝喝茶,
聊聊你的想法

15806283912
(9:00AM-6:00PM)

一切从沟通开始

洽谈合作
752718920@qq.com

工作日12小时内回复

微信号
shenhua861584

欢迎每一个对事业怀
有疯狂激情的人

登录 发布 快速回复 返回顶部 返回列表