Spring study notes---Quick start with SpringBoot
- Spring study notes---SpringBoot
- 1 Introduction to SpringBoot
- 2 configuration files
- 3 SpringBoot integrates junit
- 4 SpringBoot integrates mybatis
- 5 cases
Spring study notes—SpringBoot
Today’s goals:
- Master the steps of program development based on SpringBoot framework
- Proficient in using SpringBoot configuration information to modify server configuration
- Complete SSM integration project development based on SpringBoot
1 Introduction to SpringBoot
SpringBoot
is Pivotal
a brand new framework provided by the team and is designed to be usedsimplify Spring
AppliedInitial setupas well asdevelopment process。
Using Spring
the framework has simplified our development. And SpringBoot
it Spring
simplifies the development, so you can imagine SpringBoot
the simplicity and widespread use. Since SpringBoot
is used to simplify Spring
development, let's review it first, taking SpringMVC
development as an example:
- Create a project and
pom.xml
configure the dependent coordinates in the configuration file
-
Write
web3.0
the configuration classAs
web
a program,web3.0
the configuration class is indispensable, and this configuration class is quite troublesome. The code is as follows
-
Write
SpringMVC
the configuration class
To do this is just to put up the project framework. To be accessed by the outside world, at least you need to provide a Controller
class and a method in the class.
- Write
Controller
class
From the above SpringMVC
program development, we can see that the first three steps are all about setting up the environment, and these three steps are basically fixed. SpringBoot
This is to simplify these three steps. Next, we use an introductory case to demonstrate SpingBoot
simplified Spring
development.
1.1 SpringBoot Quick Start
1.1.1 Development steps
SpringBoot
It is very simple to develop and is divided into the following steps:
- Create a new module, select Spring initialization, and configure basic information about the module
- Select the technology set to be used by the current module
- Develop controller class
- Run the automatically generated Application class
After knowing SpringBoot
the development steps of , let’s proceed with the specific operations
1.1.1.1 Create new module
-
Click
+
SelectNew Module
Create New Module
-
Select
Spring Initializr
, used to createSpringBoot
the projectWhat we chose before is
Maven
, today we chooseSpring Initializr
to quickly buildSpringBoot
the project. InModule SDK
this item, select the version we installedJDK
.
-
SpringBoot
Make relevant settings for the projectThe projects we build using this method
SpringBoot
are actuallyMaven
projects, and this method is just a quick way to build.
Note: The packaging method here needs to be set to
Jar
-
Select
Web
and then tickSpring Web
Since we need to develop a
web
program that usesSpringMVC
technology, check the red box as shown below.
-
The interface in the picture below does not require any modification. Just click
Finish
to completeSpringBoot
the construction of the project.
After the above steps, a module with the following structure is created. It will help us automatically generate a Application
class, which will be used when starting the server later.
Notice:
There is no need to create a configuration class in the created project
The created project will automatically generate some other files, but these files currently have no use for us, so these files can be deleted.
The directories and files that can be deleted are as follows:
.mvn
.gitignore
HELP.md
mvnw
mvnw.cmd
1.1.1.2 CreateController
com.itheima.controller
Created under the package , BookController
the code is as follows:
@RestController
@RequestMapping("/books")
public class BookController {
@GetMapping("/{id}")
public String getById(@PathVariable Integer id){
System.out.println("id ==> "+id);
return "hello , spring boot!";
}
}
1.1.1.3 Start the server
SpringBoot
There is no need to use local and plug-ins to run the project. Only the classes under Tomcat
the project package are run . We can see the following information on the console.com.itheima
Application
1.1.1.4 Conducting tests
Use Postman
tools to test our programs
Through the above introductory case, we can see that using SpringBoot
for development makes the entire development very simple. So how is it done?
To study this problem, we need to look at what is written about Application
classes and . pom.xml
Let’s take a look at the class first Applicaion
. The content of this class is as follows:
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
The things in this class are very simple, just add an @SpringBootApplication
annotation to the class, and there is only one line of code in the main method. The main method in this class is executed when we start the server.
Take another look at pom.xml
the contents of the configuration file
<?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.5.0</version>
</parent>
<groupId>com.itheima</groupId>
<artifactId>springboot_01_quickstart</artifactId>
<version>0.0.1-SNAPSHOT</version>
<!--JDK 的版本-->
<properties>
<java.version>8</java.version>
</properties>
<dependencies>
<!--该依赖就是我们在创建 SpringBoot 工程勾选的那个 Spring Web 产生的-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</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>
The reason why our code can be simplified is because of the specified parent project and Spring Web
dependency implementation. We will talk about the details later.
1.1.2 Comparison
After finishing SpringBoot
the introductory case, let's compare Spring
the program and SpringBoot
the program. As shown below
-
coordinate
Spring
The coordinates in the program need to be written by yourself, and there are many coordinatesSpringBoot
The coordinates in the program are automatically generated by checking when we create the project. -
web3.0 configuration class
Spring
The program needs to write this configuration class by itself. Everyone has written this configuration class before, and it must feel very complicated.SpringBoot
The program does not need to be written by ourselves -
Configuration class
Spring/SpringMVC
The configuration class of the program needs to be written by yourself. The programSpringBoot
does not need to be written.
Spring Initializr
Note: Rapid construction of projects based on IdeaSpringBoot
requires an Internet connection.
1.1.3 Official website construction project
In the entry-level case, SpringBoot
the project can be built quickly because it is implemented Idea
using the components provided by the official website to quickly build the project. SpringBoot
So how to build projects on the official website? Build by following steps
1.1.3.1 Enter the SpringBoot official website
The official website address is as follows:
https://spring.io/projects/spring-boot
After entering SpringBoot
the official website, drag it to the bottom and you will see the following content
Then click Spring Initializr
the hyperlink and it will jump to the following page
Does the content of this page look familiar? It is basically the same as the interface we use to use the Idea
Quick Build SpringBoot
project. Enter the corresponding information on the page above
1.1.3.2 Select dependencies
To select, Spring Web
you can click the button in the upper right corner of the picture above ADD DEPENDENCIES... CTRL + B
, and the following interface will appear.
1.1.3.3 Generate project
After the above steps are completed, SpringBoot
the project can be generated. Click the button at the bottom of the page GENERATE CTRL + 回车
to generate the project and download it locally, as shown in the figure below
Open the downloaded compressed package and you can see that the project structure Idea
is exactly the same as the one generated using, as shown below
When opening pom.xml
the file, it also contains Spring Web
the dependencies of the parent project and.
Through the operation of the official website above, we know that the Idea
quick build SpringBoot
project in the official website is actually the quick build component of the official website. In the future, even if there is no, Idea
you can still use the official website to build SpringBoot
the project.
1.1.4 SpringBoot project quick start
1.1.4.1 Problem import
In the future, we will collaborate with front-end developers on development. If front-end developers need to test the front-end program, they need to open the server on the back end, which is subject to the back-end developers. In order to get rid of this restriction, front-end developers try to install Tomcat
and Idea
start the back-end program on their own computers, which is obviously unrealistic.
Our backend can SpringBoot
package the project into jar
a package. The operation of this jar
package does not depend on Tomcat
and Idea
these tools can also run normally. It is just that this package needs to connect to the same database jar
as our own program during the running process . Mysql
This can solve this problem, as shown below
So now the question is how to package it?
1.1.4.2 Packaging
Since we have configured the following plug-ins SpringBoot
in when building the projectpom.xml
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
So we only need to use Maven
the package
command package to target
generate the corresponding Jar
package in the directory.
jar
Note: This plug-in must be configured, otherwise there will be problems with the packaged package.
1.1.4.3 Startup
Enter jar
the location of the package and 命令提示符
enter the following command in
jar -jar springboot_01_quickstart-0.0.1-SNAPSHOT.jar
Execute the above command to see SpringBoot
the running log information.
1.2 SpringBoot Overview
SpringBoot
is a brand new framework provided by the Pivotal team and is designed tosimplifySpring applicationInitial setupas well asdevelopment process。
Everyone has already experienced SpringBoot
the program. Let's look back and see SpringBoot
what its main function is, which is to simplify Spring
the construction process and development process.
There are the following problems in the original Spring
environment construction and development:
- Configuration is cumbersome
- Dependency setup is cumbersome
SpringBoot
The advantages of the program happen to be aimed at Spring
the disadvantages of
- Automatic configuration. This is used to solve
Spring
the problem of complicated program configuration. - Start dependent. This is used to solve
Spring
the problem of cumbersome program dependency settings. - Accessibility (built-in server,…). We
SpringBoot
use neither localtomcat
nortomcat
plug-ins when starting the program, but useSpringBoot
the built-in server.
Next, let’s talk about SpringBoot
the starting dependencies of
1.2.1 Starting dependencies
Many dependencies containing are automatically generated in the configuration file of the project we Spring Initializr
created using the method , as shown belowMaven
pom.xml
starter
These dependencies areStartup dependencies, let’s explore how he achieves it.
1.2.1.1 Explore the parent project
From the above file, we can see that a parent project is specified. We enter the parent project and find that another parent project is specified in the parent project, as shown in the figure below
Then enter the parent project. In this project, we can see the configuration content structure as shown below
The tags in the figure above properties
define the versions that each technical software depends on, which avoids us considering version compatibility issues when using different software technologies. In properties
, we find the versions of servlet
and mysql
as shown below
dependencyManagement
The tag is for dependency version locking, but the corresponding dependency is not imported; if our project needs that dependency, we only need to introduce the dependency groupid
and artifactId
do not need to be defined version
.
The version of the plug-in is also build
locked in the tag, as shown below
After reading pom.xml
the configuration in the parent project, it is not difficult to understand why the dependencies of our project are not configured version
.
1.2.1.2 Exploring dependencies
pom.xml
The following dependencies are configured in the project we created
Enter the dependency and check pom.xml
the dependencies. You will find that it introduces the following dependencies:
It introduces the dependencies of spring-web
and spring-webmvc
, which is why our project can still use springMVC
the annotations in without relying on these two packages.
As for dependencies spring-boot-starter-tomcat
, we can basically confirm the internal dependencies from their names tomcat
, so our project can start normally.
Conclusion: If you need to use technology in the future, you only need to introduce the starting dependencies corresponding to the technology.
1.2.1.3 Summary
starter
SpringBoot
Common project names in , which define all project coordinates used by the current project to achieve the purpose of reducing dependency configuration.
parent
-
All
SpringBoot
projects to be inherited define several coordinate version numbers (dependency management, not dependency) to achieve the purpose of reducing dependency conflicts. -
spring-boot-starter-parent
spring-boot-starter-parent
There are a total of 57 different coordinate versions between (2.5.0) and (2.4.6).
actual development
-
When using arbitrary coordinates, only write G and A in GAV, V is provided by SpringBoot
G:groupid
A:artifactId
V:version
-
If a coordinate error occurs, specify the version again (be careful of version conflicts)
1.2.2 Program startup
Every program created SpringBoot
contains a class similar to the following. We call this class the bootstrap class.
@SpringBootApplication
public class Springboot01QuickstartApplication {
public static void main(String[] args) {
SpringApplication.run(Springboot01QuickstartApplication.class, args);
}
}
Notice:
-
SpringBoot
When creating a project, use the jar packaging method -
SpringBoot
The boot class is the entry point of the project, andmain
the project can be started by running the methodBecause we
pom.xml
configuredspring-boot-starter-web
the dependency in , and the dependency knows its dependencies through previous learningtomcat
, so the runmain
method can be used totomcat
start our project.
1.2.3 Switch web server
Now that we are using the server to start the project tomcat
, can we use the server tomcat
instead of using jetty
the server? jetty
In our maven
advanced version, we will talk about maven
the server used by the private server. To switch servers, you need to exclude the web
default server. How to exclude it? tomcat
Use exclusion
tag
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<artifactId>spring-boot-starter-tomcat</artifactId>
<groupId>org.springframework.boot</groupId>
</exclusion>
</exclusions>
</dependency>
Now can we run the bootstrap class? Try running it. The printed log information is as follows:
The program stopped directly, why? That's because if you exclude tomcat
the server, there will be no server in the program. Therefore, not only should tomcat
the server be excluded at this time, but jetty
the server should also be introduced. in pom.xml
because jetty
the starting dependency of
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
Next, run the boot class again. You can see in the log information that jetty
the server is used.
summary:
By switching servers, it is not difficult to find that when using SpringBoot
switching technologies, we only need to import the starting dependencies of the technology.
2 configuration files
2.1 Configuration file format
The default port number when we start the server now is 8080
, and the access path can be written as
http://localhost:8080/books/1
In the online environment, we still want to change the port number to 80
so that we don’t need to write the port number when accessing, as follows
http://localhost/books/1
And SpringBoot
how to modify the program? SpringBoot
Provides a variety of property configuration methods
-
application.properties
server.port=80
-
application.yml
server: port: 81
-
application.yaml
server: port: 82
Note:
SpringBoot
The program's configuration file name must beapplication
, only the suffix name is different.
2.1.1 Environment preparation
Create a new project springboot_02_base_config
to demonstrate different configuration files. The project environment is exactly the same as the introductory case, and the structure is as follows:
com.itheima.controller
Create a controller named under the package in the project BookController
. The content is as follows:
@RestController
@RequestMapping("/books")
public class BookController {
@GetMapping("/{id}")
public String getById(@PathVariable Integer id){
System.out.println("id ==> "+id);
return "hello , spring boot!";
}
}
2.1.2 Demonstration of different configuration files
- application.properties configuration file
Now we need to configure, the matching file must be placed resources
in the directory, and there is a application.properties
configuration file named in this directory, we can modify the port number in the configuration file, write in the configuration file port
, Idea
it will prompt, as follows
application.properties
The content of the configuration file is as follows:
server.port=80
When the service is started, log information will be printed on the console. From the log information, you can see that the bound port number has been modified.
- application.yml configuration file
Delete application.properties
the contents of the configuration file. resources
Create a configuration file named under application.yml
and write the configuration item of the port number in the file in the following format:
server:
port: 81
Note: After
:
, a space must be added before the data.
There is also a prompt function in yml
the configuration file. We can also write in the file port
, and then idea
it will be prompted and written in the above format.
Start the service and you can see on the console that the bound port number is81
- application.yaml configuration file
Delete application.yml
the configuration file and application.properties
the content of the configuration file, and then create a configuration file named resources
under . The configuration content is the same as the content in the configuration file with application.yaml
the suffix , but a different suffix is used.yml
application.yaml
The content of the configuration file is as follows:
server:
port: 83
Start the service and you can see the bound port number on the console.
Note: If there is no prompt in the cooperation file, you can use the following method to solve the problem
-
Click
File
to selectProject Structure
-
The following window will pop up, click on the red box marked in the picture to select
-
After the above operation, the following window will pop up
-
Click on the icon in the picture above
+
to pop up the configuration file for selecting the module.
-
After passing the above steps, you will see the following interface.
properties
There is one matching file for the type andymal
two configuration files for the type
2.1.3 Priority of three matching files
Configure different port numbers in the three cooperation files, start the service and check the bound port number. In this way you can see which configuration file has a higher priority
application.properties
The contents of the file are as follows:
server.port=80
application.yml
The contents of the file are as follows:
server:
port: 81
application.yaml
The contents of the file are as follows:
server:
port: 82
Start the service and you can see the port number used in the console 80
. Description application.properties
has the highest priority
Comment out application.properties
the configuration file contents. Start the service again. You can see the port number used in the console 81
, indicating that application.yml
the configuration file is the second priority.
From the above verification results, it can be determined that the priorities of the three configuration files are:
application.properties
> application.yml
> application.yaml
Notice:
SpringBoot
The core configuration file is namedapplication
SpringBoot
There are too many built-in attributes, and all attributes are modified together. When using, modify the attributes through the prompt key + keywords.For example, when you want to set the log level, you can write it in the configuration file
logging
and it will be prompted. The configuration content is as followslogging: level: root: info
2.2 yaml format
We talked about three different types of configuration files above, and properties
we have studied the type of matching files before. Next, we will focus on yaml
the type of configuration files.
YAML (YAML Ain't Markup Language) , a data serialization format . Configuration files in this format have become dominant in recent years, so this configuration file has some advantages over the configuration files used in the early days. Let’s first look at the configuration files used before.
At first we used xml
the following format:
<enterprise>
<name>itcast</name>
<age>16</age>
<tel>4006184000</tel>
</enterprise>
properties
The configuration file of type is as follows
enterprise.name=itcast
enterprise.age=16
enterprise.tel=4006184000
yaml
The content of the type configuration file is as follows
enterprise:
name: itcast
age: 16
tel: 4006184000
advantage:
-
easy to read
yaml
Type configuration filesxml
are easier to read and have a clearer structure than type configuration files -
Easy to interact with scripting languages
-
Taking data as the core, focusing on data and ignoring format
yaml
More data-focused andxml
format-focused
YAML file extension:
.yml
(mainstream).yaml
Both of the above suffix names are acceptable, and the one that will be used more in the future will be used yml
.
2.2.1 Grammar rules
-
Case Sensitive
-
Use multiple lines to describe the attribute hierarchical relationship, and use a colon at the end of each line.
-
Use indentation to indicate hierarchical relationships, align to the left of the same level, and only spaces are allowed (the Tab key is not allowed)
The number of spaces does not matter, as long as the left alignment of the same level is ensured.
-
Add a space in front of the attribute value (use colon + space as a separation between the attribute name and attribute value)
-
# represents comments
Core rule: data should be separated by spaces and colons
For array data, a minus sign is used as the data start symbol below the data writing position. One data is written in each line, and the minus sign is separated from the data by a space, for example
enterprise:
name: itcast
age: 16
tel: 4006184000
subject:
- Java
- 前端
- 大数据
2.3 Reading yaml configuration file data
2.3.1 Environment preparation
Create a new project named with the following directory springboot_03_read_data
structureSpringBoot
Create a controller named in com.itheima.controller
the package BookController
with the following content:
@RestController
@RequestMapping("/books")
public class BookController {
@GetMapping("/{id}")
public String getById(@PathVariable Integer id){
System.out.println("id ==> "+id);
return "hello , spring boot!";
}
}
com.itheima.domain
Create an entity class named under the package, etc. Enterprise
, which will be used to encapsulate data. The content is as follows
public class Enterprise {
private String name;
private int age;
private String tel;
private String[] subject;
//setter and getter
//toString
}
resources
Create a configuration file named under application.yml
, with different data configured in it. The content is as follows
lesson: SpringBoot
server:
port: 80
enterprise:
name: itcast
age: 16
tel: 4006184000
subject:
- Java
- 前端
- 大数据
2.3.2 Read configuration data
2.3.2.1 Using @Value annotation
Use @Value("表达式")
annotations to read data from the matching file. The reference method for reading attribute names in the annotations is:${一级属性名.二级属性名……}
We can BookController
use @Value
annotations in to retrieve the matching file data, as follows
@RestController
@RequestMapping("/books")
public class BookController {
@Value("${lesson}")
private String lesson;
@Value("${server.port}")
private Integer port;
@Value("${enterprise.subject[0]}")
private String subject_00;
@GetMapping("/{id}")
public String getById(@PathVariable Integer id){
System.out.println(lesson);
System.out.println(port);
System.out.println(subject_00);
return "hello , spring boot!";
}
}
2.3.2.2 Environment object
The data read in the above method is particularly scattered. SpringBoot
You can also use @Autowired
the annotation injection Environment
object to read the data. This method SpringBoot
will encapsulate all the data in the configuration file into Environment
the object. If you need to use which data, you only need to get it by calling the method Environment
of the object . getProperty(String name)
The specific code is as follows:
@RestController
@RequestMapping("/books")
public class BookController {
@Autowired
private Environment env;
@GetMapping("/{id}")
public String getById(@PathVariable Integer id){
System.out.println(env.getProperty("lesson"));
System.out.println(env.getProperty("enterprise.name"));
System.out.println(env.getProperty("enterprise.subject[0]"));
return "hello , spring boot!";
}
}
Note: In this way, the framework contains a large amount of data, which we rarely use in development.
2.3.2.3 Custom objects
SpringBoot
It also provides a way to encapsulate the data in the configuration file into our custom entity class object. The specific operations are as follows:
-
bean
Leave the creation of entity classes toSpring
management.@Component
Add annotations to the class -
Use
@ConfigurationProperties
the annotation to load the configuration fileprefix
You can also use the attribute in this annotation to specify that only the data with the specified prefix is loaded. -
BookController
Inject in
The specific code is as follows:
Enterprise
The content of the entity class is as follows:
@Component
@ConfigurationProperties(prefix = "enterprise")
public class Enterprise {
private String name;
private int age;
private String tel;
private String[] subject;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public String[] getSubject() {
return subject;
}
public void setSubject(String[] subject) {
this.subject = subject;
}
@Override
public String toString() {
return "Enterprise{" +
"name='" + name + '\'' +
", age=" + age +
", tel='" + tel + '\'' +
", subject=" + Arrays.toString(subject) +
'}';
}
}
BookController
The content is as follows:
@RestController
@RequestMapping("/books")
public class BookController {
@Autowired
private Enterprise enterprise;
@GetMapping("/{id}")
public String getById(@PathVariable Integer id){
System.out.println(enterprise.getName());
System.out.println(enterprise.getAge());
System.out.println(enterprise.getSubject());
System.out.println(enterprise.getTel());
System.out.println(enterprise.getSubject()[0]);
return "hello , spring boot!";
}
}
Notice:
Using the third method, there is the following warning prompt on the entity class
The solution to this warning is pom.xml
to add the following dependencies in
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
2.4 Multi-environment configuration
In the future, at work, the configurations of the development environment, test environment, and production environment will definitely be different. For example, during the development stage, we will install it on our own computer and connect it to our own computer. However, after the project is developed, we need to go mysql
online mysql
. This configuration changes the environment configuration to the online environment.
Modifying configurations back and forth can be troublesome, but SpringBoot
provides developers with quick configurations for multiple environments. When you need to switch environments, you only need to change one configuration. Different types of configuration files have different configurations for multi-environment development. Next, different types of configuration files are explained.
2.4.1 yaml file
application.yml
Use in to ---
separate different configurations, the content is as follows
#开发
spring:
profiles: dev #给开发环境起的名字
server:
port: 80
---
#生产
spring:
profiles: pro #给生产环境起的名字
server:
port: 81
---
#测试
spring:
profiles: test #给测试环境起的名字
server:
port: 82
---
In the above configuration spring.profiles
, is used to name different configurations. And how to tell SpringBoot
which configuration to use? You can use the following configuration to enable both configurations
#设置启用的环境
spring:
profiles:
active: dev #表示使用的是开发环境的配置
To sum up, application.yml
the content of the configuration file is as follows
#设置启用的环境
spring:
profiles:
active: dev
---
#开发
spring:
profiles: dev
server:
port: 80
---
#生产
spring:
profiles: pro
server:
port: 81
---
#测试
spring:
profiles: test
server:
port: 82
---
Notice:
The configuration items used to name the different configurations in the above configuration spring.profiles
are obsolete. The latest configuration item used to name is
#开发
spring:
config:
activate:
on-profile: dev
2.4.2 properties file
properties
Types of configuration files need to define different configuration files to configure multiple environments.
-
application-dev.properties
Is the configuration file of the development environment. We configure the port number in this file as80
server.port=80
-
application-test.properties
Is the configuration file of the test environment. We configure the port number in this file as81
server.port=81
-
application-pro.properties
Is the configuration file for the production environment. We configure the port number in this file as82
server.port=82
SpringBoot
Only the configuration file named will be loaded by default application.properties
, so you need to application.properties
set which configuration file to enable in the configuration file. The configuration is as follows:
spring.profiles.active=pro
2.4.3 Command line startup parameter settings
SpringBoot
Programs developed using will be packaged in the future jar
, and java -jar xxx.jar
services will be started via . So there is a question, how to switch environments? Because the configuration file is included in the jar package.
We know that jar
a package is actually a compressed package, which can be decompressed, modified, and finally made into a jar package. This method is obviously a bit troublesome, but SpringBoot
provides jar
a way to set up a specified environment at runtime, as follows
java –jar xxx.jar –-spring.profiles.active=test
So can the port number be temporarily modified in this way? It is also possible, you can do it in the following ways
java –jar xxx.jar –-server.port=88
Of course, you can also set multiple configurations at the same time, such as specifying which environment configuration to enable and temporarily specifying the port, as follows
java –jar springboot.jar –-server.port=88 –-spring.profiles.active=test
After testing, you will find that the port number set on the command line has a high priority (that is, the port number set on the command line is used). The configured priority has actually been SpringBoot
explained on the official website. See:
SpringBoot official website configuration priority
https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-external-config
After entering the above website, you will see the following page
If multiple methods are used to match the same configuration item, the one with higher priority will take effect.
2.5 Configuration file classification
There is a scenario where we need testers to conduct testing after we complete development. Since many configurations of the test environment and development environment are different, testers need to temporarily modify many configurations when running our project, as follows
java –jar springboot.jar –-spring.profiles.active=test --server.port=85 --server.servlet.context-path=/heima --server.tomcat.connection-timeout=-1 …… …… …… …… ……
In response to this situation, SpringBoot
different placement locations of configuration files are defined; and the priorities of placement in different locations are different.
SpringBoot
Intermediate level 4 configuration file placement location:
- 1级:classpath:application.yml
- 2级:classpath:config/application.yml
- Level 3: file: application.yml
- 4级:file :config/application.yml
illustrate: The higher the level, the higher the priority.
2.5.1 Code demonstration
Here we only demonstrate the priority of different levels of configuration file placement.
2.5.1.1 Environment preparation
Create a project named with the following directory springboot_06_config_file
structureSpringBoot
resources
Create a directory named under config
, create a configuration file in the directory application.yml
, and set the port number in the configuration file to 81
, the content is as follows
server:
port: 81
In the configuration file created resources
under application.yml
and set the port number to 80
, the content is as follows
server:
port: 80
2.5.1.2 Verify priority levels 1 and 2
Run the startup boot class and you can see the following log information on the console
From this result it can be concluded thatConfiguration files under the classpath config
take precedence over configuration files under the classpath.
2.5.1.3 Verify priority levels 2 and 4
To verify Level 4, follow these steps to complete
-
Package the project into
jar
packagesClick on the project
package
tojar
package
-
jar
Find the location of the package on your hard drive
-
Create a folder where
jar
the package is locatedconfig
, create a configuration file under this folderapplication.yml
, and set the port number in the coordination file to82
-
Run the program using the following command on the command line
java -jar springboot_06_config_file-0.0.1-SNAPSHOT.jar
The log information after running is as follows
From this result it can be concluded that
config
Configuration files under file: take precedence over configuration files under the classpath.
Notice:
There is a bug in SpringBoot version 2.5.0. When we use this version, we need to create a folder with any name in the directory
jar
where we are located.config
3 SpringBoot integrates junit
Review Spring
Integrationjunit
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class UserServiceTest {
@Autowired
private BookService bookService;
@Test
public void testSave(){
bookService.save();
}
}
Use @RunWith
annotations to specify the runner, and use @ContextConfiguration
annotations to specify the configuration class or configuration file. The SpringBoot
integration junit
is particularly simple and can be completed in the following three steps:
SpringBootTest
Add annotations to the test class- Use to
@Autowired
inject the resource to be tested - Define test methods for testing
3.1 Environment preparation
Create a project named. The project directory structure is as springboot_07_test
followsSpringBoot
Create an interface com.itheima.service
underBookService
public interface BookService {
public void save();
}
Create a class in com.itheima.service.impl
the package BookServiceImpl
and make it implement BookService
the interface, the content is as follows
@Service
public class BookServiceImpl implements BookService {
@Override
public void save() {
System.out.println("book service is running ...");
}
}
3.2 Writing test classes
test/java
Create a package under com.itheima
, create a test class under this package, and BookService
inject into the test class
@SpringBootTest
class Springboot07TestApplicationTests {
@Autowired
private BookService bookService;
@Test
public void save() {
bookService.save();
}
}
==Note:==The package where the boot class is located here must be the package where the test class is located and its sub-packages.
For example:
- The package where the bootstrap class is located is
com.itheima
- The package where the test class is located is
com.itheima
If this requirement is not met, you need to
@SpringBootTest
useclasses
the attribute to specify the bytecode object of the boot class when using annotations. like@SpringBootTest(classes = Springboot07TestApplication.class)
4 SpringBoot integrates mybatis
4.1 Review of Spring’s integration of Mybatis
Spring
Integration Mybatis
requires defining many configuration classes
-
SpringConfig
Configuration class-
Import
JdbcConfig
configuration class -
Import
MybatisConfig
configuration class@Configuration @ComponentScan("com.itheima") @PropertySource("classpath:jdbc.properties") @Import({ JdbcConfig.class,MyBatisConfig.class}) public class SpringConfig { }
-
-
JdbcConfig
Configuration class -
Define data source (load properties configuration items: driver, url, username, password)
public class JdbcConfig { @Value("${jdbc.driver}") private String driver; @Value("${jdbc.url}") private String url; @Value("${jdbc.username}") private String userName; @Value("${jdbc.password}") private String password; @Bean public DataSource getDataSource(){ DruidDataSource ds = new DruidDataSource(); ds.setDriverClassName(driver); ds.setUrl(url); ds.setUsername(userName); ds.setPassword(password); return ds; } }
-
MybatisConfig
Configuration class-
definition
SqlSessionFactoryBean
-
Define mapping configuration
@Bean public MapperScannerConfigurer getMapperScannerConfigurer(){ MapperScannerConfigurer msc = new MapperScannerConfigurer(); msc.setBasePackage("com.itheima.dao"); return msc; } @Bean public SqlSessionFactoryBean getSqlSessionFactoryBean(DataSource dataSource){ SqlSessionFactoryBean ssfb = new SqlSessionFactoryBean(); ssfb.setTypeAliasesPackage("com.itheima.domain"); ssfb.setDataSource(dataSource); return ssfb; }
-
4.2 SpringBoot integrates mybatis
4.2.1 Creating modules
-
Create a new module, select
Spring Initializr
, and configure basic information about the module
-
Select the technology set to be used by the current module (MyBatis, MySQL)
4.2.2 Define entity classes
com.itheima.domain
Define the entity class under the package , Book
the content is as follows
public class Book {
private Integer id;
private String name;
private String type;
private String description;
//setter and getter
//toString
}
4.2.3 Define dao interface
com.itheima.dao
Define the interface under the package , BookDao
the content is as follows
public interface BookDao {
@Select("select * from tbl_book where id = #{id}")
public Book getById(Integer id);
}
4.2.4 Define test classes
test/java
Define the package under com.itheima
and test the class under this package. The content is as follows
@SpringBootTest
class Springboot08MybatisApplicationTests {
@Autowired
private BookDao bookDao;
@Test
void testGetById() {
Book book = bookDao.getById(1);
System.out.println(book);
}
}
4.2.5 Writing configuration
Our code does not specify which database to connect to, what the username is, and what the password is. So this part needs to SpringBoot
be matched in the configuration file.
application.yml
Configure the following content in the configuration file
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/ssm_db
username: root
password: root
4.2.6 Testing
When we run the test method, we will see the following error message
The error message shows that there is no type Spring
in the container . Why does this happen?BookDao
bean
The reason is that Mybatis
the interface will be scanned and the code object that creates the interface will be handed over to Spring
management, but now it does not tell Mybatis
which dao
interface is it. To solve this problem, we need to BookDao
use it on the interface @Mapper
. BookDao
The interface is improved to
@Mapper
public interface BookDao {
@Select("select * from tbl_book where id = #{id}")
public Book getById(Integer id);
}
Notice:
SpringBoot
If the version is lower than 2.4.3 (not included) and the Mysql driver version is greater than 8.0, you need to configure the time zone in the URL connection string
jdbc:mysql://localhost:3306/ssm_db?serverTimezone=UTC
or configure the time zone on the MySQL database side to solve this problem.
4.2.7 Using Druid data sources
Now we have not specified the data source. SpringBoot
There is a default data source. We can also specify Druid
the data source and follow the following steps to achieve it.
-
Import
Druid
dependencies<dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.16</version> </dependency>
-
In
application.yml
the configuration file configurationYou can
spring.datasource.type
configure what data source to use through . The configuration file content can be improved tospring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/ssm_db?serverTimezone=UTC username: root password: root type: com.alibaba.druid.pool.DruidDataSource
5 cases
SpringBoot
This is the end of the study. Next, we will SSM
use the case of integrating the three major frameworks we did during the study SpringBoot
to implement it. To complete this case, we basically copy what we did before and modify it into SpringBoot
. It is mainly completed from the following parts.
-
pom.xml
Configure starting dependencies and necessary resource coordinates (druid)
-
application.yml
Set data source, port, etc.
-
Configuration class
delete all
-
dao
Set up @Mapper
-
Test class
-
page
Place it in the static directory under the resources directory
5.1 Create project
Create SpringBoot
a project. When creating a project, you need to check web
, mysql
, mybatis
and the project directory structure is as follows
Since it is used in our project Druid
, we need to import Druid
the coordinates of
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.16</version>
</dependency>
5.2 Code copy
Copy the code and test code springmvc_11_page
in the project java
together with the package to springboot_09_ssm
the project, and copy as shown below
The content that needs to be modified is as follows:
-
Springmvc_11_page
Underconfig
the package are configuration classes, andSpringBoot
the project does not need these configuration classes, so these can be deleted directly. -
dao
When copying the interface under the package to the project, you need to add annotationsspringboot_09-ssm
to the interface.@Mapper
example:
-
BookServiceTest
Testing needs to be changed toSpringBoot
integratedjunit
@SpringBootTest public class BookServiceTest { @Autowired private BookService bookService; @Test public void testGetById(){ Book book = bookService.getById(2); System.out.println(book); } @Test public void testGetAll(){ List<Book> all = bookService.getAll(); System.out.println(all); } }
5.3 Configuration file
application.yml
The following content needs to be configured in the configuration file
- Service port number
- Database connection information
- data source
server:
port: 80
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/ssm_db #?servierTimezone=UTC
username: root
password: root
5.4 Static resources
SpringBoot
There is no webapp
directory in the program, so SpringBoot
where do static resources need to be placed in the program?
Static resources need to be placed resources
under static
, as shown in the figure below