[Java Learning Summary] SpringBoot

I. Overview

1、Spring

Spring is a lightweight Inversion of Control (IoC) and Aspect-Oriented (AOP) container open source framework.
Spring was created to solve the complexity of enterprise-level application development and simplify development.
In 2002, Rod Johnson first launched the interface21 framework, the prototype of the Spring framework.
On March 24, 2004, the Spring framework was redesigned based on the interface21 framework, and the official version 1.0 was released.
Spring official website: https://spring.io/

2、SpringBoot

SpringBoot is a javaweb development framework, similar to SpringMVC.
The core idea of ​​SpringBoot is to simplify development, convention is greater than configuration , you can "just run", can quickly develop web applications, and develop an http interface with a few lines of code.
Spring Boot is developed based on Spring. Spring Boot itself does not provide the core features and extended functions of the Spring framework, but is only used to quickly and agilely develop a new generation of applications based on the Spring framework. In other words, it is not a solution to replace Spring, but a tool that is closely integrated with the Spring framework to improve the Spring developer experience. With the core idea of ​​convention being greater than configuration, Spring Boot helps us make a lot of settings by default. Most Spring Boot applications only need a small amount of Spring configuration. At the same time, it integrates a large number of commonly used third-party library configurations (such as Redis, MongoDB, Jpa, RabbitMQ, Quartz, etc.), and these third-party libraries in SpringBoot applications can be used almost out of the box with zero configuration.
To put it simply, SpringBoot is not a new framework. It configures many frameworks by default, just like maven integrates all jar packages, and spring boot integrates all frameworks.

2. Create a new HelloWorld project

1. Create a project

Method 1. Create and download a project on the official website

  1. Open Spring official website: https://start.spring.io/
  2. Fill in the project information
    insert image description here
  3. Click the GRNERATING button to download the SpringBoot project
  4. Import the downloaded project into IDEA, which is our first helloWorld project

Method 2: Create a SpringBoot project directly in IDEA

  1. Open IDEA and create a new project
  2. Choose Spring Initalizr

insert image description here

  1. Fill in the relevant information of the project in the entered interface

2. Project structure

After opening the helloWorld project, I found several files including HelloWorldApplication.java, pom.xml, application.properties and HelloWorldApplicationTests.java.
(1) pom.xml
This file is the pom file of the Maven project, which includes project dependencies and other information

<?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
is the main startup class of the SpringBoot project. When starting the project, you only need to run the main method of the startup class

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) The configuration file of application.properties
SpringBoot is an empty file when creating a new project. Then configure according to your own needs.
(4) HelloWorldApplicationTests.java
SpringBoot test class.

package com.example.helloWorld;

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

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

3. Start the HelloWorld project

First write a Controller class

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";
    }
}

Run the main method of HelloWorldApplication.java to start SpringBoot.
Visit localhost:8080/hello, the page displays hello, World. The project started successfully.
insert image description here

4. Change the banner pattern when SpringBoot starts

When SpringBoot is started normally, the console will print out Spring eggs.
insert image description here
Just one step: go to the resources directory under the project to create a new banner.txt.
The pattern can be generated at: https://www.bootschool.net/ascii , and then copied to the file!
Suddenly in banner.txt is the menu pattern generated when SpringBoot starts.
Copy the pattern of the upper reachable duck in banner.txt:

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

Then start SpringBoot, and you can see that the egg pattern turned into a reachable duck.
insert image description here

3. Multi-environment switching

Profile is Spring’s support for different configuration functions in different environments. You can quickly switch environments by activating different environment versions; when
we write the main configuration file, the file name can be application-{profile}.properties/yml, use To specify multiple environment versions, for example: application-test.properties represents the test environment configuration application-dev.properties represents the development environment configuration.
But Springboot does not start these configuration files directly, it uses the application.properties main configuration file by default;
we need to select the environment to be activated through a configuration:

spring.profiles.active=dev

It is the same as in the properties configuration file, but it is more convenient to use yml to implement without creating multiple configuration files!

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

If both yml and properties are configured with ports at the same time, and no other environment is activated, the properties configuration
file will be used by default!
The springboot startup will scan the application.properties or application.yml files in the following locations as
the default configuration file of Spring boot.

Priority 1: Configuration files in the config folder under the project path
Priority 2: Configuration files under the project path
Priority 3: Configuration files under the config folder under the resource path
Priority 4: Configuration files under the resource path

4. The principle of automatic configuration

The implementation of automatic configuration is to search all META-INF/spring.factories configuration files from the classpath, and configure the corresponding configuration items under the org.springframework.boot.autoconfigure package. But it does not necessarily take effect. To judge whether the condition is true, as long as the corresponding start is imported, there will be a corresponding starter. With the starter, our automatic assembly will take effect.
Judging according to different current conditions, decide whether this configuration class takes effect!

  • Once this configuration class takes effect; this configuration class will add various components to the container;
  • The properties of these components are obtained from the corresponding properties class, and each property in these classes is bound to the configuration file;
  • All properties that can be configured in the configuration file are encapsulated in the xxxxProperties class;
  • What can be configured in the configuration file can refer to the attribute class corresponding to a certain function

This is how autowiring works!

the essence

1. SpringBoot startup will load a large number of automatic configuration classes
2. Let's see if the functions we need are in the automatic configuration classes written by SpringBoot by default;
3. Let's see which components are configured in this automatic configuration class; (as long as The components we want to use exist in it, so we don’t need to configure it manually)
4. When adding components to the automatic configuration class in the container, some properties will be obtained from the properties class. We only need to specify the values ​​of these properties in the configuration file;
xxxxAutoConfigurartion: automatic configuration class; add components to the container
xxxxProperties: encapsulate related properties in the configuration file;

5. Spring Data

1. Introduction to Spring Data

For the data access layer, whether it is SQL (relational database) or NOSQL (non-relational database), the bottom layer of Spring Boot adopts Spring Data for unified processing. The bottom layer of Spring Boot uses Spring Data to process various databases in a unified manner. Spring Data is also a well-known project
in Spring that is as famous as Spring Boot and Spring Cloud. Sping Data official website: https://spring.io/projects/spring-data Database-related starters: You can refer to official documents: https://docs.spring.io/spring-boot/docs/2.2.5.RELEASE/ reference/htmlsingle/#using-boot-starter



2. Spring Data integrates JDBC

(1) Create a database

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) Create a SpringBoot project for testing
Create a SpringBoot project through IDEA, and introduce Spring Web, JDBC API and MySQL Driver modules.
It is found that after the project is successfully created, the pom imports the following configuration

<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) Write a yaml configuration file to connect to the database

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) After configuring these things, we can use them directly, because SpringBoot has automatically configured for us by default
; go to the test class to test

@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();
	}
}

Result: We can see that the data source he configured for us by default is: class com.zaxxer.hikari.HikariDataSource , we did not configure it manually.
HikariDataSource is known as the fastest data source in Java WEB at present, which is better than traditional C3P0, DBCP, Tomcat
jdbc and other connection pools;
you can use spring.datasource.type to specify a custom data source type, and the value is the connection to be used The fully qualified name of the pool implementation
.

3. Addition, deletion and modification of SpringData

(1) JdbcTemplate object

1. With the data source (com.zaxxer.hikari.HikariDataSource), you can get the database connection (java.sql.Connection). With the connection, you can use the native JDBC statement to operate the database; 2.
Even if you don’t use The third-party database operation framework, such as MyBatis, etc., Spring itself also makes a lightweight package for the native JDBC, namely JdbcTemplate.
3. All CRUD methods of database operations are in JdbcTemplate.
4. Spring Boot not only provides a default data source, but also JdbcTemplate has been configured by default and placed in the container. Programmers only need to inject it themselves to use it.
5. The automatic configuration of JdbcTemplate depends on org.springframework.boot.autoconfigure. The JdbcTemplateConfiguration class under the jdbc package. JdbcTemplate mainly provides the following types of methods:

  1. execute method: can be used to execute any SQL statement, generally used to execute DDL statements;
  2. update method and batchUpdate method: the update method is used to execute statements such as adding, modifying, and deleting; the batchUpdate method is used to execute batch-related statements;
  3. query method and queryForXXX method: used to execute query-related statements;
  4. call method: used to execute stored procedures and function-related statements.

(2) test

Write a Controller, inject jdbcTemplate, and write test methods for access testing;

@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 integrates Druid

A large part of the Java program needs to operate the database. In order to improve the performance of the database, it has to use the database connection pool.
Druid is a database connection pool implementation on the Alibaba open source platform, which combines the advantages of C3P0, DBCP and other DB pools, and adds log monitoring at the same time.
Druid can monitor the DB pool connection and SQL execution very well, and it is a DB connection pool for monitoring.
Druid has deployed more than 600 applications in Alibaba, and has passed the rigorous test of large-scale deployment in the production environment for more than a year.
Spring Boot 2.0 and above use the Hikari data source by default. It can be said that Hikari and Driud are the best
data sources on the Java Web. Let's focus on how Spring Boot integrates the Druid data source and how to implement database monitoring.
Github address: https://github.com/alibaba/druid/
(1) Add Druid dependencies

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

(2) Switch the data source; it has been said before that Spring Boot 2.0 and above use the com.zaxxer.hikari.HikariDataSource data source by default, but you can specify the data source through 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) After the data source is switched, inject the DataSource into the test class, and then get it, and the output will tell whether the switch is successful;
insert image description here
(4) The switch is successful! Set data source connection initialization size, maximum number of connections, waiting time, minimum number of connections and other settings.

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) Import Log4j dependencies

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

(6) Bind the parameters in the global configuration file for DruidDataSource by yourself, and then add it to the container, instead of using the
automatic generation of Spring Boot; you need to add the DruidDataSource component to the container by yourself, and bind the properties

@Configuration
public class DruidConfig {
    
    

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

(7) Go to the test class to test it

    @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();
    }

Output result: It can be seen that the configuration parameters have taken effect!

5. Configure Druid data source monitoring

The Druid data source has monitoring functions and provides a web interface for users to view.
The first step is to set up Druid's background management page, such as login account, password, etc.; configure background management;

    //后台监控: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;
    }

After configuration, we can choose to visit: http://localhost:8080/druid/login.html
insert image description here

After logging in, enter the following interface:
insert image description here
configure Druid web monitoring filter 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;
    }

6. SpringBoot integrates MyBatis

Official document: http://mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/
Maven warehouse address: https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring -boot
-starter/2.1.1

1. Build an integrated environment and test

(1) Import the dependencies required by 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) Configure database connection information (unchanged)

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) Test whether the database connection is successful!
(4) Create an entity class and import Lombok! (Department. java)

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

(5) Create mapper directory and corresponding Mapper interface (DepartmentMapper.java)

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

(6) Corresponding Mapper mapping file (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 configuration resource filtering problem

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

Now that the mapping configuration files of myBatis have been provided, it is natural to tell spring boot the location of these files

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

(8) Write the department's DepartmentController for testing!

@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);
  	}
}

Start Project Access to test it out!

2. CRUD operation test

(1) Create a new pojo class 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) Create a new EmployeeMapper interface

//@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) Write the EmployeeMapper.xml configuration file

<?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) Write the EmployeeController class for testing

@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);
    }
}

7. Web development of SpringBoot

1. Static resource processing

Writing a request is very simple, so we need to introduce our front-end resources. There are many static resources in our project, such as css, js and other files. How does SpringBoot handle this?
If we are a web application, there will be a webapp under our main, and we used to import all the pages here
. But our current pom is packaged in the form of jar, and SpringBoot has regulations for the location of static resources!
In SpringBoot, the web configuration of SpringMVC is in the configuration class WebMvcAutoConfiguration;
we can go to see that there are many configuration methods in WebMvcAutoConfigurationAdapter;
(1) addResourceHandlers add resource processing
addResourceHandlers source code display in WebMvcAutoConfigurationAdapter, all /webjars/**, all You need to go to classpath:/META-INF/resources/webjars/ to find the corresponding resources;
the essence of Webjars is to import our static resources in the form of jar packages. We used to import a static resource file, just import it directly.
For example, if you want to use jQuery, we only need to introduce the pom dependency of the corresponding version of jQuery.

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

insert image description here
It is found that jquery.js is in org.webjars:jquery:3.4.1.
Start the project and enter: http://localhost:8080/webjars/jquery/3.4.1/jquery.js , and found that static resources can be accessed.
insert image description here

(2) Import your own static resources
So how do we import our own static resources if we use our own static resources? Let's look at the next line of code;
we go to staticPathPattern and find the second mapping rule: /** , to access any resource of the current project, it will go to the resourceProperties class, we can click in and have a look at the analysis:

// 进入方法
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 can set parameters related to our static resources; this points to the folder where it will look for resources, that is, the contents of the above array.
So it is concluded that the static resources stored in the following four directories can be identified by us:

  • “classpath:/META-INF/resources/”
  • “classpath:/resources/”
  • “classpath:/static/”
  • classpath:/public/"
    We can create a corresponding folder under the resources root directory, which can store our static files; (
    3) Customize the static resource path.
    We can also specify it through the configuration file, which folders are If we need to put static resource files, configure them in application.properties;
spring.resources.static-locations=classpath:/coding/,classpath:/hello/ 

Once you define the path of the static folder yourself, the original automatic configuration will be invalid!

2. Home page processing

(1) Website welcome page
The welcome page, all index.html pages under the static resource folder; are mapped by /**.
For example, if I visit http://localhost:8080/, I will find index.html under the static resource folder
and create a new index.html in any of the three directories above; then visit and test http://localhost: 8080/ Look at the result!
(2) Website icon
Like other static resources, Spring Boot looks for favicon.ico in the configured static content location. If such a file exists, it will automatically be used as the application's favicon.
1), close the SpringBoot default icon

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

2), put an icon in the static resource directory by yourself
3), clear the browser cache! Refresh the webpage and find that the icon has become your own!

3. MVC automatic configuration principle

Before writing the project, we need to know one more thing, which is what configuration SpringBoot has made to our SpringMVC, including how to extend and customize.
Only by figuring out all these, we will be more handy to use later. Way one: source code analysis, way two: official documents!
Official document address: https://docs.spring.io/spring-boot/docs/2.2.5.RELEASE/reference/htmlsingle/#boot-features-spring-mvc-auto-configuration
The original text of the official website is as follows:

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.

If you wish to retain Spring Boot MVC functionality and wish to add additional MVC configuration (interceptors, formatters, view controllers and other functionality), you can add your own @configuration class of type webmvcconfiguer without @EnableWebMvc. If you wish to provide a custom instance of RequestMappingHandlerMapping, RequestMappingHandlerAdapter, or ExceptionHandlerExceptionResolver, you can declare a WebMVCregistrationAdapter instance to provide such components.
If you want full control over Spring MVC, you can add your own @Configuration, annotated with @EnableWebMvc.

If we want to extend SpringMVC, all we have to do is to write a @Configuration annotation class, and the type must be WebMvcConfigurer, and the @EnableWebMvc annotation cannot be marked; we will write one ourselves; we will create a new package called config and write a class MyMvcConfig.

@Controller
public class MyMVCConfig implements WebMvcConfigurer {
    
    

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

Let's visit the browser and find that http://localhost:8080/test can be accessed.
By analyzing the source code, it can be concluded that all WebMvcConfiguration will be used, not only Spring's own configuration class, but our own configuration class will of course be called.

4. Fully take over SpringMVC

Full takeover means: SpringBoot does not need the automatic configuration of SpringMVC, everything is configured by ourselves!
Just add a @EnableWebMvc to our configuration class.
Let's see if we take over SpringMVC in an all-round way, the static resource mapping that SpringBoot configured for us before will definitely be invalid.
Test it:
Start SpringBoot before adding the @EnableWebMvc annotation to access the home page:
insert image description here

After adding the @EnableWebMvc annotation, visit the home page:
insert image description here

It can be found that SpringBoot's automatic configuration of index.html as the home page is invalid after adding the @EnableWebMvc annotation.

So the @EnableWebMvc annotation cannot be added when extending SpringMVC before. Otherwise the automatic configuration will fail. In actual development, it is not recommended to fully take over SpringMVC.

Guess you like

Origin blog.csdn.net/qq_43647936/article/details/127187862