avatar

目录
SpringBoot学习笔记

​ 笔记参考:

​ 慕课网【2小时学会SpringBoot】

​ 《JavaEE开发的颠覆者 Spring Boot实战 》

[TOC]

1 Spring Boot开始

1.1 SpringBoot介绍

- SpringBoot和SpringMVC的关系:SpringBoot是SpringMVC的升级版,两者没有必然的联系
- SpringBoot的特点
    1.化繁为简,简化配置
    2.备受关注,是下一代框架
    3.微服务的入门级微框架
- 微服务
    SpringBoot -> SpringCloud -> 微服务

- 课程目录
    1.第一个SpringBoot程序
- 官方文档:https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/reference/html/  

1.2 第一个SpringBoot应用

使用IntelliJ IDEA

具体步骤:

new prpject
-> spring initializr 
->Defaut
-> web-->web

应用创建成功后,会生成相应的目录和文件。
其中有一个Application类,它是程序的入口:表示启动springboot

@SpringBootApplication
public class FirstspringbootApplication {

    public static void main(String[] args) {
        SpringApplication.run(FirstspringbootApplication.class, args);
    }
}

springboot就是一个maven工程

写一个HelloController:

@RestController     //等同于同时加上了@Controller和@ResponseBody
public class HelloController {

    @RequestMapping("/hello")
    public String say(){
        return "hello spring boot";
    }
}

运行 Application的main(),会启动,由于springboot自动内置了servlet容器,所以不需要类似传统的方式,先部署到容器再启动容器。

http://localhost:8080/hello, 就可以在浏览器上看到

Application启动类类放在最外侧,即包含所有子包

原因:spring-boot会自动加载启动类所在包下及其子包下的所有组件.

其他启动项目的方式:

2. 进入项目根目录,在命令行写:
        mvn spring-boot:run
3. 进入项目>target目录,有jar文件
        java -jar myspringboot-0.0.1-SNAPAHOT.jar

1.3 项目属性配置

两种配置文件

默认application.properties文件

server.port=8081
server.context-path=/sb

推荐application.yml

server:
port: 8081
servlet:
context-path: /sb

port:[空格]8081 ,yml语法必须有空格

访问:http://localhost:8081/sb/hello

自定义的属性

yml:

server:
  port: 8080
  context-path: /sb

girl:
  name: B
  age: 18
  content: "name: ${name},age: ${age}"

pojo:

@ConfigurationProperties(prefix = "girl") //将yml文件中前缀为girl 的属性 注入到 此类
@Component  //bean交给Spring管理
public class Girl {
    private String name;
    private String age;
    private String content;
    //set get
}

controller:

@RestController
public class HelloController {

    //注入配置文件里的name值
    @Value("${girl.name}")
    private String name;

    //自动注入
    @Autowired
    private Girl girl;

    @RequestMapping("/hello")
    public String say(){
        String s = name+"===="+girl;
        return s;
    }
}

多环境配置

application.yml

spring:
  profiles:
    active: dev

用于开发环境的application-dev.yml

server:
    port: 8081
    servlet:
      context-path: /sb

girl:
  name: 大白
  age: 18
  content: "name: ${girl.name},age: ${girl.age}"

1.4 Controller的简单使用

@Controller
@RestController: Spring4引入,@Controller+ @ResponseBody
@RequestMapping

获取参数

@PathVariable: 获取url中的数据
@RequestParam:获取请求参数的值 
@GetMapping: 组合注解

@PathVariable

@RequestMapping("/hello/{id}")
public String say(@PathVariable Integer id){

    return id.toString();
}

url:http://localhost:8081/sb/hello/1357

@RequestParam

若url格式为 http://localhost:8081/sb/hello?id=100

则使用@RequestParam

@RequestMapping("/hello")
public String say(@RequestParam("id") Integer id){

    return id.toString();
}

@GetMapping,@PostMapping

是组合注解,@GetMapping=@RequestMapping(method=RequestMethod.GET)

2 SpringBoot运行原理

2.1 自动配置

自动配置原理:基于条件配置bean

关于自动配置的源码包:

1

查看启用和未启用的自动配置:

​ 在yml文件中添加。debug: true

​ 启动后控制台会输出Positive matches:(已启用)和Negative matches:(未启用)

2.2 运作原理

@SpringBootApplication注解是一个组合注解,源码如下

2

它的核心功能由@EnableAutoConfiguration提供。@EnableAutoConfiguration源码如下:

3

AutoConfigurationImportSelector使用SpringFactoriesLoader.loadFactoryNames方法扫描具有META-INF/spring.factories文件的jar包。

打开spring-boot-autoconfigure-2.0.2.RELEASE.jar的spring.factories,查看文件中声明了哪些自动配置

4

2.3 核心注解

简单分析@ConditionalOnWebApplication注解

5

能看出,此注解使用的条件是:OnWebApplicationCondition,下面看这个条件是如何构造的,

​ 从isWebApplication方法可以看出判断条件

2.4 实例分析:http的编码配置

分析一个简单的springboot内置自动配置功能:http的编码配置

常规:在web.xml中配置filter:

6

自动配置要满足的条件:

1)能配置CharaterEncodingFilter这个类

2)能配置encoding和farceEncoding两个参数

1. 配置参数

查看源码

7

![屏幕快照 2018-05-18 下午9.36.14](/Users/machine/Desktop/屏幕快照 2018-05-18 下午9.36.14.png)

代码说明:

​ 1)在application.yml文件中的前缀是 spring.http.encoding

​ 2)默认编码为UTF-8,若要修改,则使用spring.http.encoding.charset=”编码”

2.配置bean

8

代码解释:

​ 1)EnableConfigurationProperties属性注入

​ 2)基于条件配置bean: ConditionalOnXXXX

2.5 实战:给自定义类实现自动配置

Code
1
2
3
- 自己写一个自动配置 和 starter pom
- 要求:某个类存在时,自动配置这个类的bean,并可在applicarion.properties中设置bean
- 源码文件:springbootstarterhelllo

(1)新建maven工程

(2)在pom中添加

xml
1
2
3
4
5
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
<version>2.0.0.RELEASE</version>
</dependency>

(3)属性配置

java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix = "hello")
public class HelloProperties {
private static final String MSG = "world"; //默认配置
private String msg = MSG;

public String getMsg() {
return msg;
}

public void setMsg(String msg) {
this.msg = msg;
}
}

(4)判断依据类: 根据此类存在与否来,在创建这个类的bean

java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Hello {
private String msg;//就是要配置这个默认值(某个类的某个属性的默认值)

public String sayHello(){
return "hello "+msg;
}

public String getMsg() {
return msg;
}

public void setMsg(String msg) {
this.msg = msg;
}
}

(5)自动配置类:

java
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
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableConfigurationProperties(HelloProperties.class) //注入
@ConditionalOnClass(Hello.class) //当路径下有指定类
@ConditionalOnProperty(prefix = "hello",value = "enabled",matchIfMissing = true) //指定属性书否有指定值
public class HelloAutoConfiguration {

@Autowired
private HelloProperties helloProperties;//已含hello属性的默认值
/*
返回注入了默认值的Hello
*/
@Bean
@ConditionalOnMissingBean(Hello.class) //当容器里没有指定bean
public Hello hello(){
Hello hello = new Hello();
hello.setMsg(helloProperties.getMsg());
return hello;
}
}

(6)注册配置

9

Code
1
2
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
machine.hello.HelloAutoConfiguration

(7)将以上项目发布到本地仓库,在springboot项目中添加依赖

Code
1
2
3
4
5
<dependency>
<groupId>machine</groupId>
<artifactId>spring-boot-starter-helllo</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>

(8)使用starter

java
1
2
3
4
5
6
7
8
9
10
11
@RestController     //等同于同时加上了@Controller和@ResponseBody
public class HelloController {

@Autowired
private Hello hello; //通过spring自动配置完成的 属性默认值

@RequestMapping("/hello")
public String say(){
return "hello "+ hello.getMsg();
}
}

(9)手动配置属性,在yml中添加

Code
1
2
hello:
msg: machine

3 SpringBoot开发干货

3.1 Thymeleaf模版引擎

Code
1
2
3
1. Spring Boot包括对以下模板引擎的自动配置支持:FreeMarker  Groovy  Thymeleaf  Mustache
2. 如果可能,应避免使用JSP,当使用嵌入式servlet容器时,JSP有问题
3. Spring Boot应用推荐Thymeleaf,完美支持SpringMVC

Thymeleaf基础知识

Code
1
2
- 是一个java类库,是xml/css/html模版引擎,作为MVC的View
- 提供模块与springMVC集成,可完全替代JSP

使用语法教程见【Thymeleaf常用.md】

与SpringMVC集成

SpringBoot的Thymeleaf支持

springboot 通过哦org.springframework.boot.autoconfigure.thymeleaf实现自动配置

查看ThymeleafProperties源码,可以看到默认设置的属性,前缀为spring.thymeleaf

部分代码如下:

java
1
2
3
4
private String prefix = "classpath:/templates/";	//默认模版放置路径
private String suffix = ".html"; //默认后缀
private String mode = "HTML";
private Charset encoding;

实战

(1)新增starter pom

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

(2)pojo

java
1
2
3
4
5
public class User {
private String name;
private int age;
//set get
}

(3)Controller

java
1
2
3
4
5
6
7
8
@RequestMapping("/hello")
public String say(Model model){
User user = new User();
user.setName("黄老邪");
user.setAge(1024);
model.addAttribute("user",user);
return "main";
}

(4)页面 classpath:resources/templates

html
1
2
3
4
5
6
7
8
9
10
11
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<span th:text="${user.name}"></span>
<span th:text="${user.age}"></span>
</body>
</html>

3.2 SpringBoot整合Mybatis

基本整合

使用mybatis官方提供的mybatis-spring-boot-starter方案

官网文档:http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/index.html

https://github.com/mybatis/spring-boot-starter/wiki/Quick-Start

(1)starter pom : 选mybatis,mysql

Code
1
2
3
4
5
6
7
8
9
10
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>

(2)数据源

Code
1
2
3
4
5
datasource:
url: jdbc:mysql://10.211.55.6:3306/jdbc
username: machine
password: 4869
driver-class-name: com.mysql.jdbc.Driver

MyBatis-Spring-Boot-Starter将:

Code
1
2
3
4
- 自动检测现有的数据源
- 自动将数据源注入SqlSessionFactory
- 自动创建从SqlSessionFactory获取的SqlSessionTemplate实例
- 自动扫描您的映射器,将它们链接到SqlSessionTemplate并将它们注册到Spring上下文,以便将它们注入到bean中

(3)在启动类添加mapper包扫描

Code
1
2
3
4
5
6
7
8
9
@SpringBootApplication
@MapperScan("machine.springboot01.mapper")
public class Springboot01Application {

public static void main(String[] args) {

SpringApplication.run(Springboot01Application.class, args);
}
}

这样springboot启动时候会自动扫描包(不建议在每个mapper类中加@Mapper)

(4)Mapper类编写(基于注解,还有原始的基于xml的)

java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public interface UserMapper {

/**
* 查询所有用户
*/
@Select("SELECT * FROM USER")
@Results({ //若字段相同,Results可以不写
@Result(property = "username", column = "username"),
@Result(property = "id", column = "id")
})
List<User> getAll();
}
/**
@Select 是查询类的注解,所有的查询均使用这个
@Result 修饰返回的结果集,关联实体类属性和数据库字段一一对应,如果实体类属性和数据库属性名保持一致,就不需要这个属性来修饰。
@Insert 插入数据库使用,直接传入实体类会自动解析属性到对应的值
@Update 负责修改,也可以直接传入对象
@delete 负责删除
**/

pojo

Code
1
2
3
4
5
public class User {
private String id;
private String username;
private String email;
}

table

Code
1
2
3
4
5
6
CREATE TABLE `USER` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(20) DEFAULT NULL,
`email` varchar(40) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

(5)测试

java
1
2
3
4
5
6
7
8
9
10
11
12
@RunWith(SpringRunner.class)
@SpringBootTest
public class Springboot01ApplicationTests {

@Autowired
private UserMapper userMapper;

@Test
public void testFind(){
List<User> userList = userMapper.findAll();
}
}

关于事务

Code
1
2
3
springboot自动开启了JDBC事务管理,不需要手动添加

只要在需要使用事务的类或方法上使用@Transactional注解

逆向工程

使用maven插件方式生成逆向工程

Code
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
28
29
30
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.5</version>
<configuration>
<configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
<executions>
<execution>
<id>Generate MyBatis Artifacts</id>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
</plugin>

在以上路径添加generatorConfig.xml

使用 mvn mybatis-generator:generate 或用IEDA即可

分页插件

pagehelper项目地址https://github.com/pagehelper

https://github.com/pagehelper/pagehelper-spring-boot

pom

Code
1
2
3
4
5
6
<!-- 分页插件 -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.5</version>
</dependency>

配置

Code
1
不需要配置,自动注入配置

使用

java
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
/*
1. PageHelper.startPage 静态方法调用
- 参数说明:
pageNum 开始页数
pageSize 每页显示的数据条数
- 使用方法:
在你需要进行分页的 MyBatis 查询方法前调用 PageHelper.startPage 静态方法即可,紧跟在这个方法后的第一个MyBatis 查询方法会被进行分页。

2. 使用PageInfo的用法
*/
@Test
public void testPageHelper(){
PageHelper.startPage(0,2);
List<User> userList = userMapper.findAll();//结果userList里面只有2条数据

PageInfo page = new PageInfo(userList);//用PageInfo对结果进行包装
/*
提供了很多属性
page.getPageNum();
page.getPageSize();
page.getStartRow();//第一条记录的标号
page.getEndRow();//最后一条记录的标号
page.getTotal();//总记录数
page.getPages();//总页数
*/

}

3.3 统一异常处理器

3.4 开发热部署

基于IDEA的springboot热部署

1 关闭模版缓存

Code
1
2
3
spring:
thymeleaf:
cache: false # 关闭模版缓存,利于页面开发测试

2 pom

Code
1
2
3
4
5
6
<!--热部署-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional><!--依赖不会传递-->
</dependency>

3 IDEA设置

Code
1
2
1. preperences > Build ,Execution,Deplment > compiler > build project automatically
2. cmd+shift+a > 输入Registry回车 > 勾选 complier.automake.allow.when.app.running

效果:修改类 > 会重启

3.5 项目部署到linux

springboot部署到linux

jar形式

1 打包:mvn package

2 测试运行:java -jar XXX.jar 即可

3 注册为linux服务

(1)修改spring-boot-maven-plugin

Code
1
2
3
4
5
6
7
8
9
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<executable>true</executable>
</configuration>
</plugin>
</plugins>

然后package打包

(2)注册为linux服务

Code
1
2
3
4
5
6
1. linux安装jdk
2. 上传jar
3. 基于Systemd注册服务
见笔记【linux-基于Systemd注册服务】
4. 开启服务
sudo systemctl start machine-bootdo
文章作者: Machine
文章链接: https://machine4869.gitee.io/2018/05/18/15326725480153/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 哑舍
打赏
  • 微信
    微信
  • 支付宝
    支付宝

评论