# SpringBoot笔记

# 一.SpringBoot简介

​ Spring Boot 是Spring 公司的一个顶级项目,和Spring Framework是一个级别的。 ​ Spring Boot 实际上是利用 Spring Framework4 自动配置特性完成。编写项目时不需要编写xml文件。发展到现在,Spring Boot 已经具有很大很大的生态圈,各种主流技术已经都提供了Spring Boot 的启动器。

​ 那什么是启动器呢?

​ Spring Boot 的启动器实际上就是一个依赖。这个依赖中包含了整个这个技术的相关jar包,还包含了这个技术的自动配置,以前的绝大多数xml配置都不需要配置了。当然了,启动器也是无法实现所有内容的自动配置,所以在使用Spring Boot时还需要进行少量的配置(这个配置不是在xml中了,而是在properties或有yml中即可)。如果是Spring 自己封装的启动器,那启动器的artifactid值叫:Spring-boot-starter-XXXX,如果是第三方公司提供的启动器,那启动器的artifactid值叫:XXXX-spring-boot-starter。以后每次使用Spring Boot 整合其他技术时首先需要考虑导入启动器。

​ Spring Boot 在学习什么? ​ Spring Boot本质是Spring Framework,Spring Framework框架在项目中作用是Spring 整合各种其他技术,让其他技术使用更加方便。所以学习Spring Boot 就是在学习如何整合其他技术。

# 二.基于SpringBoot的SpringMVC项目

实现步骤:

# 1.配置依赖

新建maven项目,在pom.xml中添加一个继承(主要目的:1.配置文件 2.插件3.依赖jar)

<!-- 继承方式:添加SpringBoot启动器 -->
   <parent>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-parent</artifactId>
           <version>2.1.10.RELEASE</version>
   </parent>
   
   
<!-- 添加SpringMVC启动器依赖 -->
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <version>2.1.10.RELEASE</version>
    </dependency>
</dependencies> 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

1.1注意 在公司项目中可能会出现必须继承某个项目的时候,如果Spring Boot 用了继承的方式实现了jar包的管理,那么就不能在继承别的项目了。不利于程序后期的扩展,维护等,所以Spring boot还提供了依赖的方式。

<!-- 依赖方式:添加SpringBoot启动器 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>2.1.10.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
1
2
3
4
5
6
7
8

# 2.创建控制器

    @Controller
    public class TestController {
    		@RequestMapping("/show")
    		@ResponseBody
    		public String show(){
            		return "hello";
    		}
    }
1
2
3
4
5
6
7
8

# 3.创建启动类

@SpringBootApplication
public class TestApplication {
    public static void main(String[] args) {

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

}
1
2
3
4
5
6
7
8
9

注明:
Spring Boot 项目是基于主方法启动运行的(内置了tomcat,启动主方法的时候,就把tomcat给启动了; 然后把当前项目发布到内置的tomcat里,这一堆事都帮我们做好了),所以要有一个类,类里有main方法。这个类就叫启动类。

启动类 要求:1.启动类的位置,必须包含在一个包里,并且该包是其他文件的同包或者父包。 2.在类的上方添加注解 @SpringBootApplication 3.Spring Boot 项目自动扫描 启动类所在的包以及 启动类 所在包的子包。

# 三.SpringBoot配置文件

在Spring Boot 官方文档中可以查询到所有Spring Boot 已经整合的技术的属性 https://docs.spring.io/spring-boot/docs/2.1.13.RELEASE/reference/html/common-application-properties.html

在src/main/resources/创建配置文件。Spring Boot项目为我们 设置了两种配置文件的方式: 【第一种方式:属性文件】application.properties key=value 如:server.port=8080

【第二种方式:yml】application.yml 把属性名根据点进行拆分。如 spring: DataSource: password:值 username:值 url:值 driver-class-name:值

优点: 1.有层次感 2.配置写的更少了 注明:以后的Spring Boot 项目开发中,使用第二种配置文件的方式。但其实项目在运行的时候,还是会解析成第一种属性文件的方式!

注明:还有一个先于application.yml加载的配置文件叫做bootstrap.xml。这个配置用来程序引导的,后面学习Spring Cloud 时会用。

# 四.SpringBoot项目结构

项目名: src: main: java:-----用来写java代码的。 resource:

​ 存放配置文件。

​ public:公共资源。存放所有共享的内容,对外公开的资源内容 ​ static: 静态资源。图片,css,js。不会被服务器解析的。 ​ images:1.png
​ -----启动项目访问:http://ip:port/images/1.png (不带static) ​ css: ​ js:

​ templates: thymeleaf 页面所在目录


      webapp:  只有当前项目使用jsp做页面时。【src/main/webapp】
        WEB-INF:
            jsp:
              index.jsp

注明: A:Idea平台Maven项目,缓存特别大! 尤其是项目里引入静态资源的时候,所以要经常的清除缓存!点击平台 右侧Maven----点开项目----点开 leftcycle ---点击clean 。重启项目访问就可以了!

B:在访问静态资源的时候,一定不要把 static 名字加到访问路径下,就是标识作用,类似于下面的静态资源配置! <mvc:resources location=”/static/” mapping=”/js/**”></ mvc:resources>

C: templates :专门用来存放thymeleaf 页面的,如果项目使用的是jsp作为页面展示技术,那就不需要创建templates 文件夹。该文件夹还有个特性:跟 WEB-INF 一样。不能通过浏览器url直接访问;只能通过控制器转发过来。

D:如果使用 jsp作为页面的展示技术:jsp 需要有web结构 webapp: WEB-INF: jsp: index.jsp inde平台Maven里,需要手动额外配置jsp的解析路径:**【此处的操作需要在idea旗舰版平台下才可以】**平台File-----project Structure---Modules---点开项目,选中web----点击下面的”+”加号----选择当前项目里jsp的路径----ok----ok---Apply ok! 这回webapp路径下 就让创建jsp页面了。 【到这Spring Boot就学完了没有新东西了。接下来就是讲Spring Boot 的整合!】

# 五.SpringBoot整合MyBatis,SpringMVC

使用SpringBoot 搭建SSM框架,之前的SSM整合是Spring ,Spring MVC,MyBatis。在配置文件里要配置DataSource,SQLSessionFactoryBean,MapperScannerConfigurer,,,那么使用Spring Boot进行整合的时候,这些就都不用配置了。

# 1.创建Maven项目,添加启动器依赖

<dependencies>
        <!--1.添加SpringBoot 的启动器依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>2.1.10.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <!-- 2.添加Spring MVC的启动器依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.1.10.RELEASE</version>
        </dependency>

        <!-- 3.添加Mybatis 的启动器依赖-->
       <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.1</version>
        </dependency>
    
        <!-- 4.添加mysql数据库的驱动包依赖-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.8</version>
        </dependency>

</dependencies>
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
31

# 2.编写Spring Boot 的配置文件

src/main/resources/下创建application.yml文件

	server:
  		port: 8866
	spring:
  		datasource:
    			driver-class-name: com.mysql.jdbc.Driver
    			url: jdbc:mysql://localhost:3306/mysql
    			username: root
    			password: scotter
1
2
3
4
5
6
7
8

# 3.创建实体类Dept

src/main/java 创建Dept实体类

    	public class Dept {
    		private Long  deptno;
    		private String dname;
    		private String loc;
    
    	----get/set/有参/无参!
        }
1
2
3
4
5
6
7

# 4.创建Mapper接口

public interface DeptMapper {
   List<Dept> selectAll();
}
1
2
3

# 5.创建Mapper映射文件

Maven项目不希望在src/main/java 文件夹下存放非.java文件! 在src/main/resources 文件夹下创建配置文件! 在这里文件名可以跟接口不同名,原来必须严格对应,现在识别namespace了。

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.msb.mapper.DeptMapper" >

    <select id="selectAll" resultType="dept">
  	   select * from dept
  </select>

</mapper>
1
2
3
4
5
6
7
8
9

# 6.修改application.yml文件

因为resources 的东西,最后编译的时候 都放到了classpath下。

	mybatis:
  		mapper-locations: classpath:com/msb/mapper/*.xml
        type-aliases-package: com.msb.pojo 
1
2
3

# 7.创建service接口和实现类

public interface DeptService {
    
   List<Dept> selectAll();

}

@Service
public class DeptServiceImpl implements DeptService {

    @Autowired
    private DeptMapper deptMapper;
    
    public void setDeptMapper(DeptMapper deptMapper) {
        this.deptMapper = deptMapper;
    }
    
    /*@Transactional 当前是查询功能不需要,如果是增删改功能需要加声明式事务,方法如果出错就会进行回滚了。而且单表的增删改一般都不用放,放的都是多表的增删改功能的。*/
    public List<Dept> selectAll() {
        return deptMapper.selectAll();
    }

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

# 8.创建Controller处理器

/*@Controller*/
//@RestController 当前Controller内,所有的方法都添加一@ResponseBody这个注解
@RestController   
public class DeptController {

    @Autowired
    private DeptService deptService;
    
    public void setDeptService(DeptService deptService) {
        this.deptService = deptService;
    }

@RequestMapping("/show")

    public List<Dept> Show(){
    
            return deptService.selectAll();
    }

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

# 9.创建启动类:

接口是没有注解的 没办法自动扫描到mapper接口。手动指定mapper路径:@MapperScan("com.msb.mapper") 基本上第三方整合的时候,都要在启动类上加个注解!但是自己的基本上都不用写。

@SpringBootApplication
@MapperScan("com.msb.mapper")
 /*其实这个地方也可以不写@MapperScan,那就得每个mapper接口都要加一个@Mapper注解。*/
public class SSMApplication {
    public static void main(String[] args) {
    
        SpringApplication.run(SSMApplication.class,args);
    
    }
}
1
2
3
4
5
6
7
8
9
10

# 六.SpringBoot整合Druid

# 1.数据库连接池回顾

​ 在内存中一块空间,空间中放置N多个数据库连接对象。对象可以是处于活动状态,也可以是空闲状态的。数据库获取连接对象时不在从数据库中创建连接对象,而是从数据库连接池中获取到连接对象,当获取到连接对象后,对象处于活动状态,当连接对象使用完成后,在代码中进行连接关闭,实际上是把连接对象从活动状态变为空闲状态,而不是真正的关闭。

​ 使用场合: 当我们需要频繁的访问数据库的时候,这个时候可以使用数据库连接池!

# 2.介绍Druid

​ Druid是阿里巴巴推出的数据库连接池。结合C3P0,DBCP等数据库连接池的优点。之所以能从众多的数据库连接池中脱颖而出的原因,包含可视化管理平台(控制台页面)。

# 3.代码实现

# 3.1添加依赖

此依赖版本一定不能太高,否则和数据库驱动不匹配,无法访问控制台页面。

        <!-- 5.添加Druid启动器依赖支持-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>
1
2
3
4
5
6

# 3.2修改application.yml配置文件

spring:
  	datasource:
  	
# 使用阿里的Druid连接池
    type: com.alibaba.druid.pool.DruidDataSource 
	driver-class-name: com.mysql.jdbc.Driver

# 填写你的数据库url,登录名,密码
    url: jdbc:mysql://localhost:3306/test
    username: root
	password: root

# 连接池的配置信息
# 初始化大小,最大,最小
    druid:
      initial-size: 5
      min-idle: 5
      max-active: 20
    
     #配置获取连接等待超时的时间
      max-wait: 60000
    
     #配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
      time-between-eviction-runs-millis: 60000

	#配置一个连接在池中最小生存的时间,单位是毫秒
      min-evictable-idle-time-millis: 300000
      validation-query: select 1
      test-while-idle: true
      test-on-borrow: false
      test-on-return: false

     #打开PSCache,并且指定每个连接上PSCache的大小
      pool-prepared-statements: true
      max-pool-prepared-statement-per-connection-size: 20
      filter: satat,wall,slf4j
      connection-properties: druid.stat.mergesql\=true;druid.stat.slowsqlmillis\=5000
    
   	 #配置DruidStatFilter
  web-stat-filter:
        enabled: true
        url-pattern: "/*"
        exclusions: "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*"

    #配置DruidStatViewServlet
   stat-view-servlet:
        url-pattern: "/druid/*"
      
       #IP白名单(没有配置或者为空,则允许所有访问)
        allow: 127.0.0.1,192.168.163.1
    
       #IP黑名单(同时存在时,deny优先于allow)
        deny: 192.168.1.188
        reset-enable: false
       #登陆名
        login-username: admin
      #登陆密码
        login-password: 123456

mybatis:
      mapper-locations: classpath:com/msb/mapper/*.xml
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61

# 3.3启动运行项目

A:首先访问http://local host:8086/getall------>页面显示所以集合数据。

B:然后再访问http://localhost:8086/druid ----->页面显示druid的登录页面。

C:运行期间,如果抛出错误:java.lang.NoClassDefFoundError: org/springframework/boot/bind/RelaxedPropertyResolver

解决方案:改为使用继承的方式实现SpringBoot启动器的依赖!不在使用依赖的方式!
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.3.RELEASE</version>
</parent>
1
2
3
4
5
6

# 七.SpringBoot整合logback

# 1.介绍Logback

​ Spring Boot推荐使用logback作为日志工具。 ​ Logback日志工具是log4j创始人设计的另一个开源的日志组件,是log4j的改良版本,取代log4j的原因:更快的实现,更充分的测试,更充分的文档。 【对我们项目最重要的目的:打印执行SQL】

# 2.使用步骤

logback 日志工具依赖,已经添加到spring Boot 项目里了,所以不需要再单独添加启动器了。 直接src/main/resources/下放 logback.xml配置文件就可以直接使用了。

<?xml version="1.0" encoding="UTF-8" ?>

<configuration>

    <!-- 设置变量LOG_HOME,用于指定log日志文件存放的目录 -->
    <property name="LOG_HOME" value="${catalina.base}/logs/"/>
    
    <!-- 控制台输出 -->
    <appender name="Stdout" class="ch.qos.logback.core.ConsoleAppender">
        <!-- 日志输出编码 -->
        <layout class="ch.qos.logback.classic.PatternLayout">
    
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} -%msg%n</pattern>
        </layout>
    </appender>
    
    <!-- 按照每天生成日志文件-->
    <appender name="RollingFile" class="ch.qos.logback.core.rolling.RollingFileAppender">
    
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!--日志文件输出的文件名-->
            <fileNamePattern>${LOG_HOME}/server.%d{yyy-MM-dd}.log</fileNamePattern>
            <MaxHistory>30</MaxHistory>
        </rollingPolicy>
        <layout class="ch.qos.logback.classic.PatternLayout">
    
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} -%msg%n</pattern>
        </layout>
        <!-- 日志文件最大的大小-->
        <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
            <MaxFileSize>10MB</MaxFileSize>
        </triggeringPolicy>
    </appender>


    <!-- 日志输出级别 debug  info warn  error fetel  -->
    <root level="info">
        <appender-ref ref="Stdout"/>
        <appender-ref ref="RollingFile"/>
    </root>
    
    <logger name="com.msb.mapper" level="debug"></logger>


    <!-- 日志异步到数据库 -->
    <!--    <appender name="DB" class="ch.qos.logback.classic.db.DBAppender">
    
            <connectionSource class="ch.qos.logback.core.db.DriverManagerConnectionSource">
    
                <dataSource class="com.mchange.v2.c3p0.ComboPooledDataSource">
                    <driverClass>com.mysql.jdbc.Driver</driverClass>
                    <url>jdbc:mysql://127.0.0.1:3306/test</url>
                    <user>root</user>
                    <password>root</password>
                </dataSource>
            </connectionSource>
        </appender>-->

</configuration>
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59

# 八.SpringBoot整合JSP

在Spring Boot项目里写jsp是可以的,但是需要准备一个web项目的目录结构。

# 1.创建web目录结构,配置jsp解析路径

在src/main/ 下创建文件夹 webapp ,在webapp下创建 WEB-INF 文件夹。 之后还要配置jsp解析路径:平台File-----project Structure---Modules---点开项目,选中web----点击下面的”+”加 号----选择当前项目里jsp的路径----ok----ok---Apply ok! 这回webapp路径下 就让创建jsp页面了。

# 2.创建Controller控制器

@Controller
public class DeptController {

    @Autowired
    private DeptService deptService;
    
    public void setDeptService(DeptService deptService) {
        this.deptService = deptService;
    }
    
    @RequestMapping("/show")
    public String Show(Model model){
    
            model.addAttribute("list",deptService.selectAll());
            return "index";
    }

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

# 3.修改application.yml配置文件

spring:
     mvc:
        view:
            prefix: /WEB-INF/jsp/
            suffix: .jsp
1
2
3
4
5

# 4.添加jstl标签库的依赖

     <!-- 6. 添加jstl标签库的依赖 -->      
        <dependency>
			<groupId>jstl</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
		<dependency>
			<groupId>taglibs</groupId>
			<artifactId>standard</artifactId>
			<version>1.1.2</version>
		</dependency>
1
2
3
4
5
6
7
8
9
10
11

# 九.SpringBoot整合thymeleaf

Spring Boot 官方推荐使用thymeleaf作为 视图展示技术。 thymeleaf 就是html页面,只不过是在html页面的标签里插入thymeleaf 的语法 ,达到的效果跟jsp一样。该文件夹还有个特性:跟 WEB-INF 一样。不能通过浏览器url直接访问;所有 thymeleaf 页面必须先走控制器。

thymeleaf的 效率 高于jsp:

第一次访问:jsp----.java----.class--.html

第XXX次访问 :.class--.html

Thymeleaf: html

# 1.添加依赖

<!--7. 添加thymeleaf  的依赖-->
    <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-thymeleaf</artifactId>
          <version>2.1.10.RELEASE</version>
     </dependency>
     
 注明:SpringBoot启动器使用依赖方式,而不是继承方式!
 
 
 <!--    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.3.RELEASE</version>
    </parent>-->

    <!-- 添加SpringBoot启动器依赖:spring-boot-dependencies -->
   <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-dependencies</artifactId>
        <version>2.1.10.RELEASE</version>
        <type>pom</type>
        <scope>import</scope>
    </dependency>
     
     
     
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

# 2.创建index.html页面

在src/main/resources/ 下创建templates文件夹,并且在该文件夹下创建index.html页面

# 3.编写html页面

首先修改一下根标签:添加提示前缀

<html lang="en"  xmlns:th="http://www.thymeleaf.org">

<body>
<table>
    <tr>
        <td>部门编号</td>
        <td>部门名称</td>
        <td>部门地址</td>
    </tr>
   <tr th:each="dept:${list}">
       <td th:text="${dept.deptno}"></td>
       <td th:text="${dept.dname}"></td>
       <td th:text="${dept.loc}"></td>
   </tr>

</table>
</body>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

1

# 4.Thymeleaf语法

为了有提示,修改html页面中<html>标签为: <html xmlns:th="http://www.thymeleaf.org">

4.1 th:text属性 向html标签内部输出信息。

<!--直接向标签内部填充内容,清空原有内容 -->
<span th:text="asd"></span>
<!--从作用域中获取name输入到标签内部 -->
<span th:text="${name}"></span>
<!--获取session作用域内容 -->
<span th:text="${session.name}"></span>
1
2
3
4
5
6

4.2 th:value表单元素,设置html标签中标签元素的value属性时使用。 <input type="text" value="我是文本框"> <input type="text" th:value="${session.val}">

4.3 th:if 进行逻辑判断。如果成立该标签生效(显示),如果不成立,此标签无效(不显示)

注意:判断条件中逻辑判断符号写在${}的外面

<span th:if="${session.val} != 'lisi'">if条件判断成立</span>
1

4.4 switch 如果要实现if else if else 判断表达式,在thymeleaf要使用th:switch代替,th:case="*"表示默认,需写在最后

<div th:switch="${area}">
        <div th:case="'a'">
            <img th:src="@{/static/images/logo-A.png}">
        </div>
        <div th:case="'b'">
            <img th:src="@{/static/images/logo-B.png}">
        </div>
        <div th:case="*">
            <img th:src="@{/static/images/logo-c.png}">
        </div>
    </div>
 
1
2
3
4
5
6
7
8
9
10
11
12

4.5 th:eache

4.6 th:href 设置href的属性,取值时使用@{}取值

<a href="/show?id=5&name=zhangsan">点击提交</a>
<a th:href="@{/getshow(id=5,name='zhangsan')}">点击提交</a>
<a th:href="@{/getshow(id=5,name=${session.val})}">点击提交</a>
1
2
3

# 十.SpringBoot开发者工具包

​ 对后台代码改动比较大的话,需要重启项目;频繁重启很麻烦,如果项目特别大, 重启很浪费时间。开发者工具包可以解决 项目不需要重启,监听内容的改变。

# 1.添加依赖

        <!—8.添加:Spring Boot 的开发者工具依赖 -->
       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
           	<version>2.1.10.RELEASE</version>
            <optional>true</optional>
      </dependency>
1
2
3
4
5
6
7

# 2.导入Spring Boot打包插件

    <!--添加Spring Boot 的打包插件 -->
   <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.1.10.RELEASE</version>
                <configuration>
                    <fork>true</fork>
                </configuration>
            </plugin>
        </plugins>
   </build> 如果Spring Boot不添加打包插件,它无法打包web项目!
1
2
3
4
5
6
7
8
9
10
11
12
13

# 3.设置IDEA自动编译

A:file---setting----Build,XXXXX----compiler----Builde project automattically 复选框 勾选上

B:使用快捷键 ctrl+shift+alt+?----registry----compiler.automake.allow.when.app.running 复选框勾选上

# 4.测试

页面访问的时候,稍微有一些 延迟,要多刷新几次页面才行!

# 十一.SpringBoot整合PageHelper分页工具

SpringBoot整合PageHelper 不需要做任何配置,添加依赖后就可以直接使用。

# 1.添加依赖

<!—9.添加:pagehelper依赖 -->
       <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.12</version>
        </dependency>
1
2
3
4
5
6

# 2.编写controller代码

   @RequestMapping("/showpage")
    public ModelAndView showpage(Integer pageindex){
        ModelAndView mv=new ModelAndView();
        if(pageindex==null){
            PageHelper.startPage(1,2);
        }else{
            PageHelper.startPage(pageindex,2);
        }
        List<Dept> list=deptService.findAll();
        PageInfo<Dept> pageinfo=new PageInfo<Dept>(list);
        mv.addObject("pageinfo",pageinfo);
        return mv;
   }
1
2
3
4
5
6
7
8
9
10
11
12
13

# 3.编写页面代码

<html lang="en" xmlns:th="http://www.thymeleaf.org">
<body>
<table>

    <tr>
        <td>部门编号</td>
        <td>部门名称</td>
        <td>部门地址</td>
    </tr>
    <tr th:each="dept:${pageinfo.list}">
        <td th:text="${dept.deptno}"></td>
        <td th:text="${dept.dname}"></td>
        <td th:text="${dept.loc}"></td>
    </tr>
</table>

<div th:if="!${pageinfo.isLastPage}">
    <a th:href="@{/showpage(pageindex=${pageinfo.nextPage})}">下一页</a>
    <a th:href="@{/showpage(pageindex=${pageinfo.pages})}">尾页</a>
</div>
<div th:if="!${pageinfo.isFirstPage}">
    <a th:href="@{/showpage(pageindex=1)}">首页</a>
    <a th:href="@{/showpage(pageindex=${pageinfo.prePage})}">上一页</a>
</div>
</body>
</html>
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

# 十二.SpringBoot项目打包

​ SpringBoot 项目在进行打包的时候有一个问题? 当前项目里有没有jsp页面,如果有 ,那就只能打成war包;但是没有jsp页面,那就可以直接打成一个jar包就行了。

# 1.添加SpringBoot 的打包插件

<!--添加Spring Boot 的打包插件 -->
   <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.1.10.RELEASE</version>
                <configuration>
                    <fork>true</fork>
                </configuration>
            </plugin>
        </plugins>
   </build>
1
2
3
4
5
6
7
8
9
10
11
12
13

# 2.使用继承实现SpringBoot 核心jar包管理

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.10.RELEASE</version>
</parent>

<!--<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>2.1.10.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>-->
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# 3.进行打包

A.关闭项目 B.清除项目缓存:---点击右侧maven---点击项目下的 leftcycle---双击clean --- BUILD SUCCESS 清除缓存成功 C.正式打包: ---点击右侧maven---点击项目下的 leftcycle---双击install --- BUILD SUCCESS 打包成功

# 4.部署、启动项目

A.点开项目下的target文件包,复制打包成功后的jar文件,放到一个指定路径下,如F盘根盘符。

B. dos命令窗口进入项目jar所在地 执行命令: java -jar mybatisBoot-1.0-SNAPSHOT.jar

# 5.访问项目

http://localhost:8866/show

# 十三.异常显示页面

默认情况下,SpringBoot项目错误页面如下。

2

当项目实际上线,如果给用户显示这个页面就不是很友好。当系统出现异常时应该给用户显示更加友好的错误页面。有如下几种实现方式:

# 方式一:设置具体的状态码页面

在templates下,创建error 文件夹,创建 错误状态码.html 页面。 500----》500.html
404----》404.html

# 方式二:使用X进行模糊匹配

在templates下,创建error 文件夹,创建 数字+通配符.html 页面。 535------5XX.html 404------4XX.htm

注意:40X 或者50X的格式是错误的!

# 方式三:统一错误显示页面

在templates下,创建 error.html页面

**页面显示优先级:**方式一(具体状态码页面) > 方式二(X模糊匹配) > 方式三(统一的错误显示页面)

# 十四.异常处理方法、类

在SpringBoot项目中除了设置异常显示页面,还可以通过注解实现异常处理。 常见方式有两种: A:在控制器类中添加一个方法,结合@ExceptionHandler。但是只能对当前控制器中方法出现异常进行解决。 B:新建全局异常类,通过@ControllerAdvice结合@ExceptionHandler。当全局异常处理和局部异常处理同时存在时,局部生效(就近原则) “服务降级”或者“服务容错”

# 【异常方法】

----只局限于当前controller 类。

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public String  showExe(){
        System.out.print("进入showExe控制器里。。。。。");
        return " 出错了,别着急,马上解决,稍后在放请求!";
    }
1
2
3
4
5
6

# 【异常类】

---当前项目所有controller类 都可以走该异常类。

@ControllerAdvice  //该注解表明当前类是 异常类
public class DemoExecutionClass {
    @ExceptionHandler(ArithmeticException.class)
    @ResponseBody
    public String  showExe(){
        System.out.print("进入showExe控制器历。。。。。");
        return " 出错了,别着急,马上解决,稍后在放请求!";
    }
}     
1
2
3
4
5
6
7
8
9

# 十五.SpringBoot整合Junit4单元测试工具

SpringBoot里已经整合了很多单元测试的工具,我们在进行单元测试时,选中Junit4来实现。

# 1.添加依赖

<!—10.添加单元测试启动器 - ->
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <version>2.1.10.RELEASE</version>
 </dependency>
1
2
3
4
5
6

# 2.创建测试类

src/main/test 文件夹下 创建测试类DemoTest

@SpringBootTest( classes =SSMApplication.class)  ///指定启动类
@RunWith(SpringJUnit4ClassRunner.class)///告诉当前测试类,所使用的测试工具是 junit4
public class DemoTest {

    @Autowired
    private DeptService deptService;
    
    public void setDeptService(DeptService deptService) {
        this.deptService = deptService;
    }

    @Test
    public  void  test1(){    
        List<Dept> list= deptService.selectAll();
      	System.out.println(list.size());
   }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# 十六.SpringBoot的Bean管理

没有配置文件实现Bean标签的创建,那就创建一个java类。让java类充当配置文件。 Spring中bean对象管理的发展过程: Spring3.X---xml配置文件 Spring4.X—注解方式 Spring5.X—java类方式

# 1.实现IOC

# 1.建Maven项目,添加依赖

 <!-- <parent>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-parent</artifactId>
           <version>2.1.10.RELEASE</version>
   </parent>-->

 <dependencies>   
   <!-- 添加SpringBoot启动器依赖:spring-boot-dependencies -->
   <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-dependencies</artifactId>
        <version>2.1.10.RELEASE</version>
        <type>pom</type>
        <scope>import</scope>
    </dependency>

      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-web</artifactId>
          <version>2.1.10.RELEASE</version>
      </dependency>
  </dependencies>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

# 2.创建实体类

public class User {

   private int id;
   private String name;

}---get/set/有参/无参/toString()
1
2
3
4
5
6

# 3.创建配置类

@Configuration  ///表示,当前类是 一个 配置类
public class MyConfig {

    //通过方法, 获得bean 对象;
    //返回的访问修饰符:没要求,一般都是protected
    //返回值类型: Bean 对象类型
    //方法名: -----相当于 bean标签的id值。
    
@Bean  // @Bean  该方法专门用来创建bean对象,对象id值是 方法名。
protected User jqk(){
        User user=new User();
        user.setId(1);
        user.setName("张三");
        return user;
}
    @Bean(“def”)
    protected User def(){
        User user=new User();
        user.setId(2);
        user.setName("李四");
        return user; 
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

# 4.创建启动类

@SpringBootApplication
public class SSMApplication {

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

}
1
2
3
4
5
6
7
8
9

# 5.添加单元测试依赖

       <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-test</artifactId>
          <version>2.1.10.RELEASE</version>
          <scope>test</scope>
      </dependency>
1
2
3
4
5
6

# 6.创建测试类

@SpringBootTest(classes = TestApplication.class)
@RunWith(SpringJUnit4ClassRunner.class)  //告诉Spring Boot 我要用的测试工具是 junit4
public class MyTest {

   @Autowired
   private User user;

    public void setUser(User user) {
        this.user = user;
    }
    
    @Test
    public  void  test1(){
       System.out.println(user);
   }

}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

注明:springBoot 只用这唯一一种方式来配置Bean! 思考:如果配置类中有两个相同返回值类型的方法,测试类该怎么拿? 方式一:

	 @Autowired
     private User def;
     public void setDef(User def){
        this.def=def;
	 }
1
2
3
4
5

方式二:

    @Autowired
    @Qualifier("edf”)
    private User user;
    public void setUser(User user) {
        this.user = user;
    }
1
2
3
4
5
6

# 2.实现DI

# 1.再创建一个实体类

public class Person {

	private  User user;

}----get、set、有参、无参、toString()
1
2
3
4
5

# 2.修改配置类

 ///DI的实现方式:以参数的形式注入到依赖对象里去;参数名 是 所依赖的对象的id值。
    @Bean
    protected Person personid2(User userid1){
        Person person=new Person();
        person.setPid(122);
        person.setUser(userid1);
        return person;
    }
or
    @Bean
    protected Person personid1(){
        Person person=new Person();
        person.setPid(111);
        person.setUser(userid2());
        return person;
    }


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

# 3.修改测试类

    @Autowired
    @Qualifier("personid1")
    private Person person;
    
    @Test
    public  void  test1(){
        System.out.println(person);
   }
   
   or
   
    @Autowired
    @Qualifier("personid2")
    private Person person;
    
    @Test
    public  void  test1(){
        System.out.println(person);
   }
   
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

# 十七.SpringBoot整合拦截器

回想一下,之前我们在学习SpringMVC的时候拦截器怎么用的?新建一个类,然后实现一下HandlerInterCeptor,最后在SpringMVC的配置文件里配一个mvc: Interceptors标签。 好了,现在来看一下SpringBoot如何实现:

# 1.新建Maven项目,添加依赖

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.10.RELEASE</version>
</parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.1.10.RELEASE</version>
        </dependency>
    </dependencies>
1
2
3
4
5
6
7
8
9
10
11
12

# 2.创建Controller控制器

@Controller 
public class DemoController {

	@RequestMapping("/demo")
	@ResponseBody
    public String demo(){
            return “demo”;
    }

	@RequestMapping("/login”)
	@ResponseBody
    public String demo(){
            return “login”;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# 3.创建启动类

@SpringBootApplication ///表示当前类是Spring Boot 项目的启动类
public class TestApplication {
    public static void main(String[] args) {    
        SpringApplication.run(TestApplication.class);   
    }
}
1
2
3
4
5
6

# 4.创建拦截器

@Component
public class DemoInterCeptor implements HandlerInterCeptor{

    public boolean preHandle(String[] args) {    
        System.out.println(“执行拦截器”);
        Return false;   
    }
    
}
1
2
3
4
5
6
7
8
9

# 5.创建配置类

配置拦截器要拦截的路径:

@Configuration  ///表示,当前类是 一个 配置类
public class MyConfig implements WebMvcConfigurer{

  @AutoWired
  Private  DemoInterCeptor demoInterCeptor;

     //配置拦截器的拦截地址映射。
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(myInterCeptor).addPathPatterns("/**").excludePathPatterns("/login");

    }
====当拦截谁和不拦截同时存在时,不拦截生效!现在,除了login 其他都拦。
}
1
2
3
4
5
6
7
8
9
10
11
12
13

# 6.运行

访问login时,不拦。没有拦截器的输出语句,显示的页面有内容。 访问其他时,拦截。有拦截器的输出语句,页面没有内容显示。