Hello World

吞风吻雨葬落日 欺山赶海踏雪径

0%

SpringBoot 2.x 视频教程笔记

SpringBoot 2.x 视频教程笔记

快速上手

SpringBoot 是什么

官网说明
http://spring.io/projects/spring-boot/#overview

Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can “just run”.
We take an opinionated view of the Spring platform and third-party libraries so you can get started with minimum fuss. Most Spring Boot applications need very little Spring configuration.

Spring Boot用于简化Spring应用的配置过程。

  • 采用“约定优于配置”的开发方式
  • 学习Spring Boot就是装我各类约束与要求

目录结构

  • /src/main 项目根目录
    • /java Java代码目录
    • /resources 资源目录
    • /resources/static 静态资源
    • /resources/templates 表示层页面目录
    • /resources/application.properties SpringBoot配置文件
    • /test 测试文件目录

pom依赖

Spring官方的依赖GroupId都是 org.springframework.boot

Spring Boot父级依赖 spring-boot-starter-parent 是一个特殊的starter,它用来提供相关的Maven默认依赖。使用它之后,常用的包依赖可以省去version标签。

1
2
3
4
5
6
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.2.RELEASE</version>
<relativePath/>
</parent>

maven构建插件,以maven方式提供Spring Boot支持。比如将Spring Boot应用打包成可执行的jar或war文件。

1
2
3
4
5
6
7
8
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

Spring Boot Maven plugin的5个Goals

  • spring-boot:repackage,默认goal。在mvn package之后,再次打包可执行的jar/war,同时保留mvn package生成的jar/war为.origin
  • spring-boot:run,运行Spring Boot应用
  • spring-boot:start,在mvn integration-test阶段,进行Spring Boot应用生命周期的管理
  • spring-boot:stop,在mvn integration-test阶段,进行Spring Boot应用生命周期的管理
  • spring-boot:build-info,生成Actuator使用的构建信息文件build-info.properties

增加web支持

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

常用配置

web相关

配置项 默认值 说明
debug False 调试模式
server.port 8080 服务端口
server.servlet.context-path / 应用上下文
spring.http.encoding.charset utf-8 默认字符集编码
spring.mvc.date-format 日期输入格式
spring.jackson.date-format json日期输出格式
spring.jackson.time-zone GMT时区 (GMT+8)

日志配置

配置项 默认值 说明
logging.file 日志输出文件
logging.level.ROOT info 日志输出级别
logging.level.* info 自定义包的输出级别
logging.config logback-spring.xml 日志配置文件

设置例子

1
logging.level.org.springframework=ERROR

自定义配置的设置官方建议设置为logback-spring.xml

When possible, we recommend that you use the -spring variants for your logging configuration (for example, logback-spring.xml rather than logback.xml). If you use standard configuration locations, Spring cannot completely control log initialization.

官方文档
https://docs.spring.io/spring-boot/docs/2.1.2.RELEASE/reference/htmlsingle/#boot-features-custom-log-configuration

环境切换与自定义配置

yml 配置

yaml是一种简介的非标记语言,以数据为中心,使用空白、缩进、分行组织数据,从而使得表示更加简洁易读。

语法格式

  • 标准格式: key:[空格]value
  • 使用空格代表层级关系,以”:”结束

application.properties 配置文件在写的时候要写完整,如:

1
2
3
spring.profiles.active=dev
spring.datasource.data-username=root
spring.datasource.data-password=root

在yml 文件中配置的话,写法如下:

1
2
3
4
5
6
7
8
spring:
profiles:
active: prod
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/test
username: root
password: root

yml 文件在写的时候层次感强,而且少写了代码,同类配置聚合在一起。所以现在很多人都使用yml配置文件。

多环境配置

多个环境的配置方式

1
2
3
spring:
profiles:
active: prd

这行配置在application.yml 文件中,意思是当前起作用的配置文件是application-prd.yml,其他的配置文件命名为 application-dev.yml,application-pre.yml等。

application.yml 作为基础配置文件,环境配置文件包含相同内容时候覆盖基础配置文件。其他的会合并。

多环境的日志配置方式要求

  1. 多环境下日志需要spring的环境管理的时候必须配置文件名为logback-spring.xml
  2. 在配置文件中增加springProfile标签

配置例子

1
2
3
4
5
6
<springProfile name="dev">
<property name="LOG_HOME" value="d:/logs/dev/" />
</springProfile>
<springProfile name="prd">
<property name="LOG_HOME" value="d:/logs/prd/" />
</springProfile>

自定义配置

  • @Vlaue 单个属性的注入
  • @ConfigurationProperties 全局注入

比如配置文件

1
2
3
connection.username=admin
connection.password=kyjufskifas2jsfs
connection.remoteAddress=192.168.1.1

配置加载代码

@Value

1
2
@Value("${connection.username}")
private String username;

@ConfigurationProperties

1
2
3
4
5
6
7
8
9
@Component
@ConfigurationProperties(prefix="connection")
public class ConnectionSettings {

private String username;
private String remoteAddress;
private String password ;

...get/set

Spring Boot与MVC

web依赖的pom包:

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

Spring Boot虽然帮助简化了架构的依赖与配置过程,但是Web开发层面上,仍沿用了Spring MVC的开发方式。

Spring Boot最重要的开发环节就是开发Controller控制器。

Web开发相关注解基本都在
org.springframework.web.bind.annotation包下。核心的注解如下:

@Controller

Controller负责处理分发器DispatcherServlet分发的请求,@Controller标记的类就是一个SpringMVC Controller 对象。

@RequestMapping

@RequestMapping是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。

  1. value & method;
    value: 指定请求的实际地址,指定的地址可以是URI Template 模式;
    method: 指定请求的method类型, GET、POST、PUT、DELETE等;

  2. consumes & produces
    consumes: 指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;
    produces: 指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回;

  3. params & headers
    params: 指定request中必须包含某些参数值是,才让该方法处理。
    headers: 指定request中必须包含某些指定的header值,才能让该方法处理请求。

根据处理http方法的不同产生了几个更为方便的注解

  • @GetMapping 处理get请求
  • @PostMapping 处理post请求
  • @PutMapping put请求
  • @DeleteMapping
  • @PatchMapping

@ResponseBody

标明方法的返回值是http请求体的内容。通常返回内容是jsonxml格式时使用。

@RestController

标明此控制器是一个Rest的控制器。相当于

1
2
@Controller
@ResponseBody

@PathVariable

标明方法的参数是绑定在了URI中的。
比如

1
2
3
4
5
6
7
@RequestMapping(value="/user/{userId}/roles/{roleId}",method = RequestMethod.GET)  
public String hello(@PathVariable("userId") String userId,
@PathVariable("roleId") String roleId){
System.out.println("User Id : " + userId);
System.out.println("Role Id : " + roleId);
return "hello";
}

注意URI中的{userId}对应的是@PathVariable("userId") String userId

@RequestParam

标明方法的参数是映射了http请求参数中的。类似于request.getParameter("name")

  • value 绑定的参数名称
  • required 请求中是否必须含有此参数,boolean类型
  • defaultValue 默认值

控制器中的视图与模型

Model

model 由系统创建,只包含了Controller需要的数据模型,视图路由需要根据方法返回值来确定。方法通常是

1
return "视图名称";

ModelAndView

ModelAndView 即包含了页面渲染的模型,同时也包含了视图的的渲染路由。

方法返回值必须是 ModelAndView类型。

详见Model & ModelAndView

上传文件处理

上传文件

  1. POST请求
  2. file组件
  3. enctype=’multipart/form-data’(二进制提交)

enctype 属性
http://www.w3school.com.cn/tags/att_form_enctype.asp

上传文件Controller

  1. @RequestParam 指定上传的file组件name
  2. MultipartFile 类型的接收参数(会创建临时文件)
    接收到文件后就是文件的拷贝动作了,可以使用Spring的FileCopyUtils.copy拷贝到指定目录。

默认的请求大小配置

1
2
3
4
5
6
spring.servlet.multipart.enabled=true # Whether to enable support of multipart uploads.
spring.servlet.multipart.file-size-threshold=0B # Threshold after which files are written to disk.
spring.servlet.multipart.location= # Intermediate location of uploaded files.
spring.servlet.multipart.max-file-size=1MB # Max file size.
spring.servlet.multipart.max-request-size=10MB # Max request size.
spring.servlet.multipart.resolve-lazily=false # Whether to resolve the multipart request lazily at the time of file or parameter access.

获取表单数据

表单数据可以直接设置成entity对应的实例,只要表单name和后台实体bean的名称相同即可。

注意date类型的映射:

1
spring.mvc.date-format=yyyy-MM-dd HH:mm:ss

ps. 上传完文件后可以重定向到对应地址。

1
return new ModelAndView("redirect:/upload");

404/500

在templates中建立error目录,其中包含
404.html500.html即可。

1
2
3
4
5
6
7
8
9
src/
+- main/
+- java/
| + <source code>
+- resources/
+- public/
+- error/
| +- 404.html
+- <other public assets>

注册filter

使用FilterRegistrationBean注册filter,

exp(包含Servlet注册):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
@Bean
public ServletRegistrationBean druidStatServlet(){

ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");

Map<String,String> initMap = new HashMap<>();
initMap.put("loginUsername",userName);
initMap.put("loginPassword",password);

servletRegistrationBean.setInitParameters(initMap);
return servletRegistrationBean;
}

@Bean
public FilterRegistrationBean druidStatFilter(){
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();

filterRegistrationBean.setFilter(new WebStatFilter());
filterRegistrationBean.addUrlPatterns("/*");

Map<String,String> initMap = new HashMap<>();
initMap.put("exclusions","*.woff,.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");

filterRegistrationBean.setInitParameters(initMap);
filterRegistrationBean.setOrder(1);
return filterRegistrationBean;
}

替换默认tomcat容器

默认支持三种web容器

  • tomcat
  • jetty
  • undertow

比如替换成undertow
1.排除tomcat

1
2
3
4
5
6
7
8
9
10
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<artifactId>spring-boot-starter-tomcat</artifactId>
<groupId>org.springframework.boot</groupId>
</exclusion>
</exclusions>
</dependency>

2.增加undertow依赖

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId>
</dependency>

Spring Data与JPA

Spring Data

官网地址
https://spring.io/projects/spring-data
为不同的数据库提供统一便捷的开发方式。

JPA

Java 持久化API。
https://spring.io/projects/spring-data-jpa

Spring Boot 中Spring Data的相关文档
https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-jpa-and-spring-data

Spring Boot与MyBatis

引入mybatis

  1. mybatis-spring-boot-starter
  2. 配置application
    • mybatis.config-location
    • mybatis.mapper-location
  3. 创建mybatis-config.xml
  4. 开发mybatis应用

mybatis-spring-boot-starter

mybatis-spring-boot-starter 是由mybatis提供的,所以包名是org.mybatis.spring.boot

配置application

1
2
mybatis.config-location=classpath:/mybatis/config.xml
mybatis.mapper-locations=classpath:/mybatis/mapper/*.xml
  • config-location 指定config xml文件地址
  • mapper-locations 这个配置参数仅当mapper xml与mapper class不在同一个目录下时有效
    注意如果设置了mapper-locations 指定了mapper的路径就不需要在mybatis-config中再一次配置了mapper了。

mybatis-config.xml

mybatis-config.xml中可以配置mappers。可以不使用mybatis.mapper-locations来指定。

1
2
3
4
5
6
7
8
9
10
11
<?xml version="1.0" encoding="UTF-8" ?>
<!-- mybatis的配置文件 -->
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<mappers>
<mapper resource="/sqlmap/group_info_mapper.xml"/>
<mapper resource="/sqlmap/group_detail_mapper.xml"/>
</mappers>
</configuration>

编码式配置

适合多数据源,有多个mybatis-config的情况。

编码创建SqlSessionFactorySqlSessionTemplate

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@Configuration
@MapperScan(basePackages ={"com.alibaba.china.fuck.mapper","com.alibaba.china.fuck2.mapper"},sqlSessionFactoryRef="testDBSSF")
public class testDBMybatisConfig {

@Bean(name = "testDBSSF")
@Primary
public SqlSessionFactory testDBSqlSessionFactory(@Qualifier(value="testDBDataSource")DataSource mysql,
@Value("classpath:testdb/mybatis-config.xml") Resource configLocation) throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(mysql);
sqlSessionFactoryBean.setConfigLocation(configLocation);
return sqlSessionFactoryBean.getObject();
}

@Bean(name = "testDBSST")
public SqlSessionTemplate testDBSqlSessionTemplate(@Qualifier(value="testDBSSF")SqlSessionFactory testDBSqlSessionFactory) {
return new SqlSessionTemplate(testDBSqlSessionFactory, ExecutorType.BATCH);
}

@Bean("testDBTx")
public PlatformTransactionManager testDBTransactionManager(@Qualifier(value="testDBDataSource")DataSource takeoutDataSource) {
return new DataSourceTransactionManager(takeoutDataSource);
}
}

配置好对应的mybatis-config文件,由的mybatis-config文件直接指定mapper配置文件的路径。且由@MapperScan注解直接指定扫描mapper的包。

另外Mapper注解可以不需要对应的mapper.xml文件。配置如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.mapper;

import com.model.UserMo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

@Mapper
public interface UserMapper1 {

@Select("select id, name, money, create_date as createDate, modify_date as modifyDate, is_deleted as isDeleted" +
" from test_user where name = #{name}")
UserMo selectUserByName(@Param("name") String name);

注意这里方法的参数使用了@Param("name")注解。

Spring Boot 部署、打包与发布

jar包

默认是fat jar形式的,可以直接用java -jar xxx.jar来启动。

另外打成jar包后的spring boot应用默认会加载jar包同目录下application.properties文件,并以此文件的配置来覆盖jar中的配置。

war包(不建议)

一、 改变默认配置packaging设置成war

二、 把web容器的pom依赖的scope改成provided

三、 把application入口类失效。
入口类继承extends SpringBootServletInitializer。使其中configure方法启动时会托管给spring boot。

1
2
3
4
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(PanApplication.class);
}