【Java学习总结】SpringBoot

一、概述

1、Spring

Spring是一个轻量级的控制反转(IoC)和面向切面(AOP)的容器开源框架。
Spring是为了解决企业级应用开发的复杂性而创建的,简化开发。
2002年,Rod Jahnson首次推出了Spring框架雏形interface21框架。
2004年3月24日,Spring框架以interface21框架为基础,经过重新设计,发布了1.0正式版。
Spring官网:https://spring.io/

2、SpringBoot

SpringBoot就是一个javaweb的开发框架,和SpringMVC类似。
SpringBoot的核心思想就是简化开发,约定大于配置, you can “just run”,能迅速的开发web应用,几行代码开发一个http接口。
Spring Boot 基于 Spring 开发,Spirng Boot 本身并不提供 Spring 框架的核心特性以及扩展功能,只是用于快速、敏捷地开发新一代基于 Spring 框架的应用程序。也就是说,它并不是用来替代 Spring 的解决方案,而是和 Spring 框架紧密结合用于提升 Spring 开发者体验的工具。Spring Boot 以约定大于配置的核心思想,默认帮我们进行了很多设置,多数 Spring Boot 应用只需要很少的 Spring 配置。同时它集成了大量常用的第三方库配置(例如 Redis、MongoDB、Jpa、RabbitMQ、Quartz 等等),SpringBoot 应用中这些第三方库几乎可以零配置的开箱即用。
简单来说就是SpringBoot其实不是什么新的框架,它默认配置了很多框架的使用方式,就像maven整合了所有的jar包,spring boot整合了所有的框架 。

二、新建一个HelloWorld项目

1.创建项目

方式一、在官网创建并下载项目

  1. 打开Spring官网:https://start.spring.io/
  2. 填写项目信息
    在这里插入图片描述
  3. 点击GRNERATING按钮,即可下载SpringBoot项目
  4. 将下载好的项目导入到IDEA中,即为我们的第一个helloWorld项目

方式二、直接在IDEA中创建SpringBoot项目

  1. 打开IDEA,创建新项目
  2. 选择Spring Initalizr

在这里插入图片描述

  1. 在进入的界面中填写项目的相关信息

2.项目结构

打开helloWorld项目后发现有HelloWorldApplication.java、pom.xml、application.properties和HelloWorldApplicationTests.java几个文件。
(1)pom.xml
此文件为该Maven项目的pom文件,里面包括项目的依赖等信息

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.7.4</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>helloWorld</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>helloWorld</name>
	<description>Demo project for Spring Boot</description>
	<properties>
		<java.version>1.8</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</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>

(2)HelloWorldApplication.java
SpringBoot项目的主启动类,启动项目时只要运行该启动类的main方法即可

package com.example.helloWorld;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

(3)application.properties
SpringBoot的配置文件,新建项目时是空文件。后续根据自己的需求进行配置。
(4)HelloWorldApplicationTests.java
SpringBoot的测试类。

package com.example.helloWorld;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class HelloWorldApplicationTests {
    
    
	@Test
	void contextLoads() {
    
    
	}
}

3.启动HelloWorld项目

先编写一个Controller类

package com.example.helloworld.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    
    

    //接口:http://localhost:8080/hello
    @RequestMapping("/hello")
    public String hello() {
    
    
        //调用业务,接收前端的参数!
        return "hello,World";
    }
}

运行HelloWorldApplication.java的main方法启动SpringBoot。
访问localhost:8080/hello,页面显示出hello,World。项目成功启动。
在这里插入图片描述

4. 更改SpringBoot启动时的banner 图案

正常启动SpringBoot时,控制台会打印出Spring字样的彩蛋。
在这里插入图片描述
只需一步:到项目下的 resources 目录下新建一个banner.txt 即可。
图案可以到:https://www.bootschool.net/ascii 这个网站生成,然后拷贝到文件中即可!
banner.txt中的突然即为SpringBoot启动时生成的菜单图案。
在banner.txt中复制上可达鸭的图案:

                              ,-'   ,"",
                             / / ,-'.-'
                   _,..-----+-".".-'_,..
           ,...,."'             `--.---'
         /,..,'                     `.
       ,'  .'                         `.
      j   /                             `.
      |  /,----._           ,.----.       .
     ,  j    _   \        .'  .,   `.     |
   ,'   |        |  ____  |         | ."--+,^.
  /     |`-....-',-'    `._`--....-' _/      |
 /      |     _,'          `--..__  `        '
j       | ,-"'    `    .'         `. `        `.
|        .\                        /  |         \
|         `\                     ,'   |          \
|          |                    |   ,-|           `.
.         ,'                    |-"'  |             \
 \       /                      `.    |              .
  ` /  ,'                        |    `              |
   /  /                          |     \             |
  /  |                           |      \           /
 /   |                           |       `.       _,
.     .                         .'         `.__,.',.----,
|      `.                     ,'             .-""      /
|        `._               _.'               |        /
|           `---.......,--"                  |      ,'
'                                            '    ,'
 \                                          /   ,'
  \                                        /  ,'
   \                                      / ,'
    `.                                   ,+'
      >.                               ,'
  _.-'  `-.._                      _,-'-._
,__          `",-............,.---"       `.
   \..---. _,-'            ,'               `.
          "                '..,--.___,-"""---' mh

然后启动SpringBoot,可以看到启动的彩蛋图案变成了可达鸭。
在这里插入图片描述

三、多环境切换

profile是Spring对不同环境提供不同配置功能的支持,可以通过激活不同的环境版本,实现快速切换环境;
我们在主配置文件编写的时候,文件名可以是 application-{profile}.properties/yml , 用来指定多个环境版本,例如:application-test.properties 代表测试环境配置 application-dev.properties 代表开发环境配置。
但是Springboot并不会直接启动这些配置文件,它默认使用application.properties主配置文件;
我们需要通过一个配置来选择需要激活的环境:

spring.profiles.active=dev

和properties配置文件中一样,但是使用yml去实现不需要创建多个配置文件,更加方便了 !

server:
	port: 8081
#选择要激活那个环境块
spring:
	profiles:
		active: prod
		
 ---
server:
	port: 8083
spring:
	profiles: dev #配置环境的名称
	
---
server:
	port: 8084
spring:
	profiles: prod  #配置环境的名称

如果yml和properties同时都配置了端口,并且没有激活其他环境 , 默认会使用properties配
置文件的!
springboot 启动会扫描以下位置的application.properties或者application.yml文件作为Spring boot的
默认配置文件。

优先级1:项目路径下的config文件夹配置文件
优先级2:项目路径下配置文件
优先级3:资源路径下的config文件夹配置文件
优先级4:资源路径下配置文件

四、自动配置原理

自动配置的实现是从classpath中搜寻所有的META-INF/spring.factories配置文件 ,并将其中对应的org.springframework.boot.autoconfigure包下的配置项。但是不一定生效,要判断条件是否成立,只要导入了对应的start,就有对应的启动器了,有了启动器,我们自动装配才会生效。
根据当前不同的条件判断,决定这个配置类是否生效!

  • 一但这个配置类生效;这个配置类就会给容器中添加各种组件;
  • 这些组件的属性是从对应的properties类中获取的,这些类里面的每一个属性又是和配置文件绑定的;
  • 所有在配置文件中能配置的属性都是在xxxxProperties类中封装着;
  • 配置文件能配置什么就可以参照某个功能对应的这个属性类

这就是自动装配的原理!

精髓

1、SpringBoot启动会加载大量的自动配置类
2、我们看我们需要的功能有没有在SpringBoot默认写好的自动配置类当中;
3、我们再来看这个自动配置类中到底配置了哪些组件;(只要我们要用的组件存在在其中,我们就不需要再手动配置了)
4、给容器中自动配置类添加组件的时候,会从properties类中获取某些属性。我们只需要在配置文件中指定这些属性的值即可;
xxxxAutoConfigurartion:自动配置类;给容器中添加组件
xxxxProperties:封装配置文件中相关属性;

五、SpringData

1.SpringData简介

对于数据访问层,无论是 SQL(关系型数据库) 还是 NOSQL(非关系型数据库),Spring Boot 底层都是采用 Spring Data 的方式进行统一处理。
Spring Boot 底层都是采用 Spring Data 的方式进行统一处理各种数据库,Spring Data 也是 Spring 中
与 Spring Boot、Spring Cloud 等齐名的知名项目。
Sping Data 官网:https://spring.io/projects/spring-data
数据库相关的启动器 : 可以参考官方文档:
https://docs.spring.io/spring-boot/docs/2.2.5.RELEASE/reference/htmlsingle/#using-boot-starter

2.SpringData整合JDBC

(1)创建数据库

CREATE DATABASE /*!32312 IF NOT EXISTS*/`springboot` /*!40100 DEFAULT

CHARACTER SET utf8 */;
USE `springboot`;

/*Table structure for table `department` */
DROP TABLE IF EXISTS `department`;
CREATE TABLE `department` (
`id` int(3) NOT NULL AUTO_INCREMENT COMMENT '部门id',
`department_name` varchar(20) NOT NULL COMMENT '部门名字',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=106 DEFAULT CHARSET=utf8;
/*Data for the table `department` */
insert  into `department`(`id`,`department_name`) values (101,'技术部'),
(102,'销售部'),(103,'售后部'),(104,'后勤部'),(105,'运营部');

/*Table structure for table `employee` */
DROP TABLE IF EXISTS `employee`;
CREATE TABLE `employee` (
`id` int(5) NOT NULL AUTO_INCREMENT COMMENT '雇员id',
`last_name` varchar(100) NOT NULL COMMENT '名字',
`email` varchar(100) NOT NULL COMMENT '邮箱',
`gender` int(2) NOT NULL COMMENT '性别1 男, 0 女',
`department` int(3) NOT NULL COMMENT '部门id',
`birth` datetime NOT NULL COMMENT '生日',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1006 DEFAULT CHARSET=utf8;

/*Data for the table `employee` */
insert  into `employee`(`id`,`last_name`,`email`,`gender`,`department`,`birth`) values
(1001,'张三','[email protected]',1,101,'2020-03-06 15:04:33'),
(1002,'李四','[email protected]',1,102,'2020-03-06 15:04:36'),
(1003,'王五','[email protected]',0,103,'2020-03-06 15:04:37'),
(1004,'赵六','[email protected]',1,104,'2020-03-06 15:04:39'),
(1005,'孙七','[email protected]',0,105,'2020-03-06 15:04:45');

(2)创建测试的SpringBoot项目
通过IDEA创建SpringBoot项目,引入Spring Web、JDBC API和MySQL Driver模块。
发现项目创建成功后pom导入了如下配置

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <scope>runtime</scope>
</dependency>

(3)编写yaml配置文件连接数据库

spring:
  datasource:
    username: root
    password: 121314
    # 加入时区报错了,就增加一个时区的配置就Ok了 serverTimezone=UTC
    url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.jdbc.Driver

(4)配置完这一些东西后,我们就可以直接去使用了,因为SpringBoot已经默认帮我们进行了自动配
置;去测试类测试一下

@SpringBootTest
class SpringbootDataJdbcApplicationTests {
    
    
	//DI注入数据源
	@Autowired
	DataSource dataSource;
	@Test
	public void contextLoads() throws SQLException {
    
    
		//看一下默认数据源
		System.out.println(dataSource.getClass());
		//获得连接
		Connection connection =  dataSource.getConnection();
		System.out.println(connection);
		//关闭连接
		connection.close();
	}
}

结果:我们可以看到他默认给我们配置的数据源为 : class com.zaxxer.hikari.HikariDataSource , 我们并没有手动配置。
HikariDataSource 号称 Java WEB 当前速度最快的数据源,相比于传统的 C3P0 、DBCP、Tomcat
jdbc 等连接池更加优秀;
可以使用 spring.datasource.type 指定自定义的数据源类型,值为 要使用的连接池实现的完全限定
名。

3.SpringData的增删改查

(1)JdbcTemplate对象

1、有了数据源(com.zaxxer.hikari.HikariDataSource),然后可以拿到数据库连接(java.sql.Connection),有了连接,就可以使用原生的 JDBC 语句来操作数据库;
2、即使不使用第三方第数据库操作框架,如 MyBatis等,Spring 本身也对原生的JDBC 做了轻量级的封装,即 JdbcTemplate 。
3、数据库操作的所有 CRUD 方法都在 JdbcTemplate 中。
4、Spring Boot 不仅提供了默认的数据源,同时默认已经配置好了 JdbcTemplate 放在了容器中,程序员只需自己注入即可使用
5、JdbcTemplate 的自动配置是依赖 org.springframework.boot.autoconfigure.jdbc 包下的JdbcTemplateConfiguration 类。JdbcTemplate主要提供以下几类方法:

  1. execute方法:可以用于执行任何SQL语句,一般用于执行DDL语句;
  2. update方法及batchUpdate方法:update方法用于执行新增、修改、删除等语句;batchUpdate方法用于执行批处理相关语句;
  3. query方法及queryForXXX方法:用于执行查询相关语句;
  4. call方法:用于执行存储过程、函数相关语句。

(2)测试

编写一个Controller,注入 jdbcTemplate,编写测试方法进行访问测试;

@RestController
public class JDBCController {
    
    

    @Autowired
    JdbcTemplate jdbcTemplate;

    //查询数据库的所有信息
    //没有实体类,数据库中的东西如何获取
    @GetMapping("/userList")
    public List<Map<String, Object>> userList() {
    
    

        String sql = "select * from user";
        List<Map<String, Object>> list_maps = jdbcTemplate.queryForList(sql);

        return list_maps;
    }

    @GetMapping("/addUser")
    public String addUser() {
    
    
        String sql = "insert into mybatis.user(id,name,pwd) values (4,'小明','123456')";
        jdbcTemplate.update(sql);
        return "addUser-ok";
    }

    @GetMapping("/updateUser/{id}")
    public String updateUser(@PathVariable("id") int id) {
    
    
        String sql = "update mybatis.user set name = ?,pwd=? where id=" + id;
        //封装
        Object[] objects = new Object[2];
        objects[0] = "小明2";
        objects[1] = "zzzzzz";
        jdbcTemplate.update(sql, objects);
        return "updateUser-ok";
    }

    @GetMapping("/deleteUser/{id}")
    public String deleteUser(@PathVariable("id") int id) {
    
    
        String sql = "delete from mybatis.user where id = ?";
        jdbcTemplate.update(sql, id);
        return "deleteUser-ok";
    }
}

4.SpringBoot集成Druid

Java程序很大一部分要操作数据库,为了提高性能操作数据库的时候,又不得不使用数据库连接池。
Druid 是阿里巴巴开源平台上一个数据库连接池实现,结合了 C3P0、DBCP 等 DB 池的优点,同时加入了日志监控。
Druid 可以很好的监控 DB 池连接和 SQL 的执行情况,天生就是针对监控而生的 DB 连接池。
Druid已经在阿里巴巴部署了超过600个应用,经过一年多生产环境大规模部署的严苛考验。
Spring Boot 2.0 以上默认使用 Hikari 数据源,可以说 Hikari 与 Driud 都是当前 Java Web 上最优秀的
数据源,我们来重点介绍 Spring Boot 如何集成 Druid 数据源,如何实现数据库监控。
Github地址:https://github.com/alibaba/druid/
(1)添加上 Druid 依赖

<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>druid</artifactId>
	<version>1.1.21</version>
</dependency>

(2)切换数据源;之前已经说过 Spring Boot 2.0 以上默认使用com.zaxxer.hikari.HikariDataSource 数据源,但可以通过 spring.datasource.type 指定数据源。

spring:
  datasource:
    username: root
    password: 121314
    # 加入时区报错了,就增加一个时区的配置就Ok了 serverTimezone=UTC
    url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource

(3)数据源切换之后,在测试类中注入DataSource,然后获取到它,输出一看便知是否成功切换;
在这里插入图片描述
(4)切换成功!设置数据源连接初始化大小、最大连接数、等待时间、最小连接数等设置项。

spring:
  datasource:
    username: root
    password: 121314
    # 加入时区报错了,就增加一个时区的配置就Ok了 serverTimezone=UTC
    url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource


    #Spring Boot默认是不注入这些属性值的,需要自己绑定
    #druid 数据源专有配置
    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true

    #配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入
    #如果运行时报错 java.lang.ClassNotFoundException: org.apache.log4j.Priority
    #则导入 log4j 依赖即可,Maven地址:https://mvnrespository.com/artifact/log4j/log4j
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

(5)导入Log4j 的依赖

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

(6)自己为 DruidDataSource 绑定全局配置文件中的参数,再添加到容器中,而不再使
用 Spring Boot 的自动生成了;需要自己添加 DruidDataSource 组件到容器中,并绑定属性

@Configuration
public class DruidConfig {
    
    

    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druidDataSource() {
    
    
        return new DruidDataSource();
    }

(7)去测试类中测试一下

    @Autowired
    DataSource dataSource;

    @Test
    void contextLoads() throws SQLException {
    
    
        System.out.println(dataSource.getClass());
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
        DruidDataSource druidDataSource = (DruidDataSource) dataSource;
    	System.out.println("druidDataSource 数据源最大连接数:" + druidDataSource.getMaxActive());
    	System.out.println("druidDataSource 数据源初始化连接数:" + druidDataSource.getInitialSize());
        connection.close();
    }

输出结果 :可见配置参数已经生效!

5、配置 Druid 数据源监控

Druid 数据源具有监控的功能,并提供了一个 web 界面方便用户查看。
第一步需要设置 Druid 的后台管理页面,比如 登录账号、密码 等;配置后台管理;

    //后台监控:web.xml,ServletRegistrationBean
    //因为SpringBoot内置了servlet框架,所以没有web.xml,替代方法:ServletRegistrationBean
    @Bean
    public ServletRegistrationBean statViewServlet() {
    
    
        ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");
        //后台需要有人登陆,账号密码配置
        HashMap<String, String> initParameters = new HashMap<>();
        //增加配置
        initParameters.put("loginUsername", "root");//登录的key是固定的 loginUsername loginPassword
        initParameters.put("loginPassword", "121314");

        //允许谁可以访问
        initParameters.put("allow", "");
        //禁止谁能访问
        //initParameters.put("hi","192.168.11.123");

        bean.setInitParameters(initParameters);//设置初始化参数
        return bean;
    }

配置完毕后,我们可以选择访问 : http://localhost:8080/druid/login.html
在这里插入图片描述

登录后进入如下界面:
在这里插入图片描述
配置 Druid web 监控 filter 过滤器

    @Bean
    public FilterRegistrationBean webStatFilter() {
    
    
        FilterRegistrationBean bean = new FilterRegistrationBean<>();
        bean.setFilter(new WebStatFilter());
        //可以过滤哪些请求呢
        HashMap<String, String> initParameters = new HashMap<>();
        //这些东西不进行统计
        initParameters.put("exclusions", "*.js,*.css,/druid/*");
        bean.setInitParameters(initParameters);
        return bean;
    }

六、SpringBoot整合MyBatis

官方文档:http://mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/
Maven仓库地址:https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot
-starter/2.1.1

1、搭建整合环境并测试

(1)导入 MyBatis 所需要的依赖

        <!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.1</version>
        </dependency>

(2)配置数据库连接信息(不变)

spring.datasource.username=root
spring.datasource.password=121314
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

(3)测试数据库是否连接成功!
(4)创建实体类,导入 Lombok!(Department.java)

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Department {
    
    
	private Integer id;
	private String departmentName;
}

(5)创建mapper目录以及对应的 Mapper 接口(DepartmentMapper.java)

//@Mapper : 表示本类是一个 MyBatis 的 Mapper
@Mapper
@Repository
public interface DepartmentMapper {
    
    
  // 获取所有部门信息
  List<Department> getDepartments();
  // 通过id获得部门
  Department getDepartment(Integer id);
}

(6)对应的Mapper映射文件(DepartmentMapper.xml)

<?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.kuang.mapper.DepartmentMapper">
	<select id="getDepartments" resultType="Department">
		select * from department;
	</select>
	<select id="getDepartment" resultType="Department" parameterType="int">
		select * from department where id = #{id};
	</select>
</mapper>

(7)maven配置资源过滤问题

<resources>
  <resource>
    <directory>src/main/java</directory>
    <includes>
      <include>**/*.xml</include>
    </includes>
    <filtering>true</filtering>
  </resource>
</resources>

既然已经提供了 myBatis 的映射配置文件,自然要告诉 spring boot 这些文件的位置

# 整合mybatis
mybatis.type-aliases-package=com.example.pojo
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml

(8)编写部门的 DepartmentController 进行测试!

@RestController
public class DepartmentController {
    
    
 
  	@Autowired
  	DepartmentMapper departmentMapper;
 
	// 查询全部部门
  	@GetMapping("/getDepartments")
  	public List<Department> getDepartments(){
    
    
  	  	return departmentMapper.getDepartments();
  	}
  	// 查询全部部门
  	@GetMapping("/getDepartment/{id}")
  	public Department getDepartment(@PathVariable("id") Integer id){
    
    
  	  	return departmentMapper.getDepartment(id);
  	}
}

启动项目访问进行测试!

2、增删改查操作测试

(1)新建一个pojo类 Employee ;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Employee {
    
    
	private Integer id;
	private String lastName;
	private String email;
	private Integer gender;	//1 male, 0 female
	private Integer department;
	private Date birth;
	private Department eDepartment; // 冗余设计
}

(2)新建一个 EmployeeMapper 接口

//@Mapper : 表示本类是一个 MyBatis 的 Mapper
@Mapper
@Repository
public interface EmployeeMapper {
    
    
	// 获取所有员工信息
	List<Employee> getEmployees();
	// 新增一个员工
    int save(Employee employee);
    // 通过id获得员工信息
    Employee get(Integer id);
    // 通过id删除员工
    int delete(Integer id);
}

(3)编写 EmployeeMapper.xml 配置文件

<?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.kuang.mapper.EmployeeMapper">
	<resultMap id="EmployeeMap" type="Employee">
    	<id property="id" column="eid"/>
    	<result property="lastName" column="last_name"/>
    	<result property="email" column="email"/>
   		<result property="gender" column="gender"/>
    	<result property="birth" column="birth"/>
    	<association property="eDepartment"  javaType="Department">
     		<id property="id" column="did"/>
      		<result property="departmentName" column="dname"/>
    	</association>
	</resultMap>
	<select id="getEmployees" resultMap="EmployeeMap">
		select e.id as eid,last_name,email,gender,birth,d.id as did,d.department_name as dname from department d,employee e where d.id = e.department
	</select>
	<insert id="save" parameterType="Employee">
		insert into employee (last_name,email,gender,department,birth)
   		values (#{lastName},#{email},#{gender},#{department},#{birth});
	</insert>
	<select id="get" resultType="Employee">
   		select * from employee where id = #{id}
  	</select>
  	<delete id="delete" parameterType="int">
   		delete from employee where id = #{id}
  	</delete>
</mapper>

(4)编写EmployeeController类进行测试

@RestController
public class EmployeeController {
    
    
	@Autowired
    EmployeeMapper employeeMapper;
    // 获取所有员工信息
    @GetMapping("/getEmployees")
    public List<Employee> getEmployees(){
    
    
        return employeeMapper.getEmployees();
    }
    @GetMapping("/save")
    public int save(){
    
    
        Employee employee = new Employee();
        employee.setLastName("kuangshen");
        employee.setEmail("[email protected]");
        employee.setGender(1);
        employee.setDepartment(101);
        employee.setBirth(new Date());
        return employeeMapper.save(employee);
    }
    // 通过id获得员工信息
    @GetMapping("/get/{id}")
    public Employee get(@PathVariable("id") Integer id){
    
    
        return employeeMapper.get(id);
    }
    // 通过id删除员工
    @GetMapping("/delete/{id}")
    public int delete(@PathVariable("id") Integer id){
    
    
        return employeeMapper.delete(id);
    }
}

七、SpringBoot的Web开发

1、静态资源处理

写请求非常简单,那我们要引入我们前端资源,我们项目中有许多的静态资源,比如css,js等文件,这个SpringBoot怎么处理呢?
如果我们是一个web应用,我们的main下会有一个webapp,我们以前都是将所有的页面导在这里面
的。但是我们现在的pom,打包方式是为jar的方式,SpringBoot对于静态资源放置的位置,是有规定的!
SpringBoot中,SpringMVC的web配置都在 WebMvcAutoConfiguration 这个配置类里面;
我们可以去看看 WebMvcAutoConfigurationAdapter 中有很多配置方法;
(1)addResourceHandlers 添加资源处理
WebMvcAutoConfigurationAdapter 中的addResourceHandlers 源码展示,所有的 /webjars/** , 都需要去 classpath:/META-INF/resources/webjars/ 找对应的资源;
Webjars本质就是以jar包的方式引入我们的静态资源, 我们以前要导入一个静态资源文件,直接导入即可。
例如如果要使用jQuery,我们只要要引入jQuery对应版本的pom依赖即可。

<dependency>
    <groupId>org.webjars</groupId>
    <artifactId>jquery</artifactId>
    <version>3.4.1</version>
</dependency>

在这里插入图片描述
发现jquery.js就在org.webjars:jquery:3.4.1中。
启动项目进入:http://localhost:8080/webjars/jquery/3.4.1/jquery.js,发现可以访问静态资源。
在这里插入图片描述

(2)导入自己的静态资源
那我们项目中要是使用自己的静态资源该怎么导入呢?我们看下一行代码;
我们去找staticPathPattern发现第二种映射规则 : /** , 访问当前的项目任意资源,它会去找resourceProperties 这个类,我们可以点进去看一下分析:

// 进入方法
public String[] getStaticLocations() {
    
    
	return this.staticLocations;
}
// 找到对应的值
private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;
// 找到路径
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
    
    
	"classpath:/META-INF/resources/",
	"classpath:/resources/",
	"classpath:/static/",
	"classpath:/public/"
};

ResourceProperties 可以设置和我们静态资源有关的参数;这里面指向了它会去寻找资源的文件夹,即上面数组的内容。
所以得出结论,以下四个目录存放的静态资源可以被我们识别:

  • “classpath:/META-INF/resources/”
  • “classpath:/resources/”
  • “classpath:/static/”
  • classpath:/public/"
    我们可以在resources根目录下新建对应的文件夹,都可以存放我们的静态文件;
    (3)自定义静态资源路径
    我们也可以自己通过配置文件来指定一下,哪些文件夹是需要我们放静态资源文件的,在application.properties中配置;
spring.resources.static-locations=classpath:/coding/,classpath:/hello/ 

一旦自己定义了静态文件夹的路径,原来的自动配置就都会失效了!

2、首页处理

(1)网站欢迎页
欢迎页,静态资源文件夹下的所有 index.html 页面;被 /** 映射。
比如我访问 http://localhost:8080/ ,就会找静态资源文件夹下的 index.html
新建一个 index.html ,在我们上面的3个目录中任意一个;然后访问测试 http://localhost:8080/ 看结果!
(2)网站图标
与其他静态资源一样,Spring Boot在配置的静态内容位置中查找 favicon.ico。如果存在这样的文件,它将自动用作应用程序的favicon。
1)、关闭SpringBoot默认图标

spring.mvc.favicon.enabled=false # 关闭默认图标

2)、自己放一个图标在静态资源目录下
3)、清除浏览器缓存!刷新网页,发现图标已经变成自己的了!

3、MVC自动配置原理

在进行项目编写前,我们还需要知道一个东西,就是SpringBoot对我们的SpringMVC还做了哪些配置,包括如何扩展,如何定制。
只有把这些都搞清楚了,我们在之后使用才会更加得心应手。 途径一:源码分析,途径二:官方文档!
官方文档地址 :https://docs.spring.io/spring-boot/docs/2.2.5.RELEASE/reference/htmlsingle/#boot-feature s-spring-mvc-auto-configuration
官网原文如下:

If you want to keep Spring Boot MVC features and you want to add additional MVC configuration
(interceptors, formatters, view controllers, and other features), you can add your own @Configuration class of type WebMvcConfigurer but without @EnableWebMvc.
If you wish to provide custom instances of RequestMappingHandlerMapping, RequestMappingHandlerAdapter, or ExceptionHandlerExceptionResolver, you can declare a WebMvcRegistrationsAdapter instance to provide such components.
If you want to take complete control of Spring MVC, you can add your own @Configuration annotated with @EnableWebMvc.

如果您希望保留Spring Boot MVC功能,并且希望添加其他MVC配置(拦截器、格式化程序、视图控制器和其他功能),则可以添加自己的@configuration类,类型为webmvcconfiguer,但不添加@EnableWebMvc。如果希望提供RequestMappingHandlerMapping、RequestMappingHandlerAdapter或ExceptionHandlerExceptionResolver的自定义实例,则可以声明WebMVCregistrationAdapter实例来提供此类组件。
如果您想完全控制Spring MVC,可以添加自己的@Configuration,并用@EnableWebMvc进行注释。

如果要扩展SpringMVC,我们要做的就是编写一个@Configuration注解类,并且类型要为WebMvcConfigurer,还不能标注@EnableWebMvc注解;我们去自己写一个;我们新建一个包叫config,写一个类MyMvcConfig。

@Controller
public class MyMVCConfig implements WebMvcConfigurer {
    
    

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
    
    
        registry.addViewController("/test").setViewName("test");
    }
}  

我们去浏览器访问一下,发现http://localhost:8080/test可以访问过来。
通过分析源码可以得出结论:所有的WebMvcConfiguration都会被作用,不止Spring自己的配置类,我们自己的配置类当然也会被调用。

4、全面接管SpringMVC

全面接管即:SpringBoot对SpringMVC的自动配置不需要了,所有都是我们自己去配置!
只需在我们的配置类中要加一个@EnableWebMvc。
我们看下如果我们全面接管了SpringMVC了,我们之前SpringBoot给我们配置的静态资源映射一定会无效。
测试一下:
不加@EnableWebMvc注解前启动SpringBoot访问首页:
在这里插入图片描述

加了@EnableWebMvc注解后访问首页:
在这里插入图片描述

可以发现,加了@EnableWebMvc注解后SpringBoot对index.html为首页的自动配置失效了。

所以在之前扩展SpringMVC时不能加@EnableWebMvc注解。否则自动配置将失效。在实际开发中,不建议全面接管SpringMVC。

猜你喜欢

转载自blog.csdn.net/qq_43647936/article/details/127187862