Spring study notes---Quick start with SpringBoot

Spring study notes---Quick start with SpringBoot

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

SpringBootis Pivotala brand new framework provided by the team and is designed to be usedsimplify SpringAppliedInitial setupas well asdevelopment process

Using Springthe framework has simplified our development. And SpringBootit Springsimplifies the development, so you can imagine SpringBootthe simplicity and widespread use. Since SpringBootis used to simplify Springdevelopment, let's review it first, taking SpringMVCdevelopment as an example:

  1. Create a project and pom.xmlconfigure the dependent coordinates in the configuration file

Insert image description here

  1. Write web3.0the configuration class

    As weba program, web3.0the configuration class is indispensable, and this configuration class is quite troublesome. The code is as follows
    Insert image description here

  2. Write SpringMVCthe configuration class
    Insert image description here

​ 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 Controllerclass and a method in the class.

  1. Write Controllerclass

Insert image description here

From the above SpringMVCprogram development, we can see that the first three steps are all about setting up the environment, and these three steps are basically fixed. SpringBootThis is to simplify these three steps. Next, we use an introductory case to demonstrate SpingBootsimplified Springdevelopment.

1.1 SpringBoot Quick Start

1.1.1 Development steps

SpringBootIt 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 SpringBootthe development steps of , let’s proceed with the specific operations

1.1.1.1 Create new module
  • Click +Select New ModuleCreate New Module
    Insert image description here

  • Select Spring Initializr, used to create SpringBootthe project

    What we chose before is Maven, today we choose Spring Initializrto quickly build SpringBootthe project. In Module SDKthis item, select the version we installed JDK.

Insert image description here

  • SpringBootMake relevant settings for the project

    The projects we build using this method SpringBootare actually Mavenprojects, and this method is just a quick way to build.
    Insert image description here

    Note: The packaging method here needs to be set toJar

  • Select Weband then tickSpring Web

    Since we need to develop a webprogram that uses SpringMVCtechnology, check the red box as shown below.
    Insert image description here

  • The interface in the picture below does not require any modification. Just click Finishto complete SpringBootthe construction of the project.

Insert image description here

After the above steps, a module with the following structure is created. It will help us automatically generate a Applicationclass, which will be used when starting the server later.

Insert image description here

Notice:

  1. There is no need to create a configuration class in the created project

  2. 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.controllerCreated under the package , BookControllerthe 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

SpringBootThere is no need to use local and plug-ins to run the project. Only the classes under Tomcatthe project package are run . We can see the following information on the console.com.itheimaApplication
Insert image description here

1.1.1.4 Conducting tests

Use Postmantools to test our programs

Insert image description here

Through the above introductory case, we can see that using SpringBootfor 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 Applicationclasses and . pom.xmlLet’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 @SpringBootApplicationannotation 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.xmlthe 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 Webdependency implementation. We will talk about the details later.

1.1.2 Comparison

After finishing SpringBootthe introductory case, let's compare Springthe program and SpringBootthe program. As shown below
Insert image description here

  • coordinate

    SpringThe coordinates in the program need to be written by yourself, and there are many coordinates

    SpringBootThe coordinates in the program are automatically generated by checking when we create the project.

  • web3.0 configuration class

    SpringThe program needs to write this configuration class by itself. Everyone has written this configuration class before, and it must feel very complicated.

    SpringBootThe program does not need to be written by ourselves

  • Configuration class

    Spring/SpringMVCThe configuration class of the program needs to be written by yourself. The program SpringBootdoes not need to be written.

Spring InitializrNote: Rapid construction of projects based on Idea SpringBootrequires an Internet connection.

1.1.3 Official website construction project

In the entry-level case, SpringBootthe project can be built quickly because it is implemented Ideausing the components provided by the official website to quickly build the project. SpringBootSo 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 SpringBootthe official website, drag it to the bottom and you will see the following content
Insert image description here

Then click Spring Initializrthe hyperlink and it will jump to the following page

Insert image description here

Does the content of this page look familiar? It is basically the same as the interface we use to use the IdeaQuick Build SpringBootproject. Enter the corresponding information on the page above

1.1.3.2 Select dependencies

To select, Spring Webyou can click the button in the upper right corner of the picture above ADD DEPENDENCIES... CTRL + B, and the following interface will appear.
Insert image description here

1.1.3.3 Generate project

After the above steps are completed, SpringBootthe 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

Insert image description here

Open the downloaded compressed package and you can see that the project structure Ideais exactly the same as the one generated using, as shown below
Insert image description here

When opening pom.xmlthe file, it also contains Spring Webthe dependencies of the parent project and.

Through the operation of the official website above, we know that the Ideaquick build SpringBootproject in the official website is actually the quick build component of the official website. In the future, even if there is no, Ideayou can still use the official website to build SpringBootthe project.

1.1.4 SpringBoot project quick start

1.1.4.1 Problem import

Insert image description here

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 Tomcatand Ideastart the back-end program on their own computers, which is obviously unrealistic.

Our backend can SpringBootpackage the project into jara package. The operation of this jarpackage does not depend on Tomcatand Ideathese tools can also run normally. It is just that this package needs to connect to the same database jaras our own program during the running process . MysqlThis can solve this problem, as shown below
Insert image description here

So now the question is how to package it?

1.1.4.2 Packaging

Since we have configured the following plug-ins SpringBootin when building the projectpom.xml

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
</plugin>

So we only need to use Maventhe packagecommand package to targetgenerate the corresponding Jarpackage in the directory.

jarNote: This plug-in must be configured, otherwise there will be problems with the packaged package.

1.1.4.3 Startup

Enter jarthe 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 SpringBootthe running log information.

Insert image description here

1.2 SpringBoot Overview

SpringBootis a brand new framework provided by the Pivotal team and is designed tosimplifySpring applicationInitial setupas well asdevelopment process

Everyone has already experienced SpringBootthe program. Let's look back and see SpringBootwhat its main function is, which is to simplify Springthe construction process and development process.

There are the following problems in the original Springenvironment construction and development:

  • Configuration is cumbersome
  • Dependency setup is cumbersome

SpringBootThe advantages of the program happen to be aimed at Springthe disadvantages of

  • Automatic configuration. This is used to solve Springthe problem of complicated program configuration.
  • Start dependent. This is used to solve Springthe problem of cumbersome program dependency settings.
  • Accessibility (built-in server,…). We SpringBootuse neither local tomcatnor tomcatplug-ins when starting the program, but use SpringBootthe built-in server.

Next, let’s talk about SpringBootthe starting dependencies of

1.2.1 Starting dependencies

Many dependencies containing are automatically generated in the configuration file of the project we Spring Initializrcreated using the method , as shown belowMavenpom.xmlstarter
Insert image description here

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
Insert image description here

Then enter the parent project. In this project, we can see the configuration content structure as shown below
Insert image description here

The tags in the figure above propertiesdefine 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 servletand mysqlas shown below
Insert image description here

dependencyManagementThe 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 groupidand artifactIddo not need to be defined version.

The version of the plug-in is also buildlocked in the tag, as shown below
Insert image description here

After reading pom.xmlthe 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.xmlThe following dependencies are configured in the project we created
Insert image description here

Enter the dependency and check pom.xmlthe dependencies. You will find that it introduces the following dependencies:
Insert image description here

It introduces the dependencies of spring-weband spring-webmvc, which is why our project can still use springMVCthe 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

  • SpringBootCommon project names in , which define all project coordinates used by the current project to achieve the purpose of reducing dependency configuration.

parent

  • All SpringBootprojects to be inherited define several coordinate version numbers (dependency management, not dependency) to achieve the purpose of reducing dependency conflicts.

  • spring-boot-starter-parentspring-boot-starter-parentThere 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 SpringBootcontains 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:

  • SpringBootWhen creating a project, use the jar packaging method

  • SpringBootThe boot class is the entry point of the project, and mainthe project can be started by running the method

    Because we pom.xmlconfigured spring-boot-starter-webthe dependency in , and the dependency knows its dependencies through previous learning tomcat, so the run mainmethod can be used to tomcatstart 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 tomcatinstead of using jettythe server? jettyIn our mavenadvanced version, we will talk about maventhe server used by the private server. To switch servers, you need to exclude the webdefault server. How to exclude it? tomcatUse exclusiontag

<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:
Insert image description here

The program stopped directly, why? That's because if you exclude tomcatthe server, there will be no server in the program. Therefore, not only should tomcatthe server be excluded at this time, but jettythe server should also be introduced. in pom.xmlbecause jettythe 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 jettythe server is used.
Insert image description here

summary:

By switching servers, it is not difficult to find that when using SpringBootswitching 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 80so that we don’t need to write the port number when accessing, as follows

http://localhost/books/1

And SpringBoothow to modify the program? SpringBootProvides a variety of property configuration methods

  • application.properties

    server.port=80
    
  • application.yml

    server:
    	port: 81
    
  • application.yaml

    server:
    	port: 82
    

Note: SpringBootThe program's configuration file name must be application, only the suffix name is different.

2.1.1 Environment preparation

Create a new project springboot_02_base_configto demonstrate different configuration files. The project environment is exactly the same as the introductory case, and the structure is as follows:
Insert image description here

com.itheima.controllerCreate 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 resourcesin the directory, and there is a application.propertiesconfiguration file named in this directory, we can modify the port number in the configuration file, write in the configuration file port, Ideait will prompt, as follows
Insert image description here

application.propertiesThe 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.
Insert image description here

  • application.yml configuration file

Delete application.propertiesthe contents of the configuration file. resourcesCreate a configuration file named under application.ymland 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 ymlthe configuration file. We can also write in the file port, and then ideait will be prompted and written in the above format.
Insert image description here

Start the service and you can see on the console that the bound port number is81
Insert image description here

  • application.yaml configuration file

Delete application.ymlthe configuration file and application.propertiesthe content of the configuration file, and then create a configuration file named resourcesunder . The configuration content is the same as the content in the configuration file with application.yamlthe suffix , but a different suffix is ​​used.yml

application.yamlThe 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.
Insert image description here

Note: If there is no prompt in the cooperation file, you can use the following method to solve the problem

  • Click Fileto selectProject Structure
    Insert image description here

  • The following window will pop up, click on the red box marked in the picture to select
    Insert image description here

  • After the above operation, the following window will pop up
    Insert image description here

  • Click on the icon in the picture above +to pop up the configuration file for selecting the module.
    Insert image description here

  • After passing the above steps, you will see the following interface. propertiesThere is one matching file for the type and ymaltwo configuration files for the type
    Insert image description here

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.propertiesThe contents of the file are as follows:

server.port=80

application.ymlThe contents of the file are as follows:

server:
	port: 81

application.yamlThe 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.propertieshas the highest priority

Comment out application.propertiesthe configuration file contents. Start the service again. You can see the port number used in the console 81, indicating that application.ymlthe 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:

  • SpringBootThe core configuration file is namedapplication

  • SpringBootThere 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 loggingand it will be prompted. The configuration content is as follows

    logging:
      level:
        root: info
    

2.2 yaml format

We talked about three different types of configuration files above, and propertieswe have studied the type of matching files before. Next, we will focus on yamlthe type of configuration files.
Insert image description here

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 xmlthe following format:

<enterprise>
    <name>itcast</name>
    <age>16</age>
    <tel>4006184000</tel>
</enterprise>

propertiesThe configuration file of type is as follows

enterprise.name=itcast
enterprise.age=16
enterprise.tel=4006184000

yamlThe content of the type configuration file is as follows

enterprise:
	name: itcast
	age: 16
	tel: 4006184000

advantage:

  • easy to read

    yamlType configuration files xmlare 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

    yamlMore data-focused and xmlformat-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_datastructureSpringBoot
Insert image description here

Create a controller named in com.itheima.controllerthe package BookControllerwith 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.domainCreate 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
}

resourcesCreate 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 BookControlleruse @Valueannotations 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. SpringBootYou can also use @Autowiredthe annotation injection Environmentobject to read the data. This method SpringBootwill encapsulate all the data in the configuration file into Environmentthe object. If you need to use which data, you only need to get it by calling the method Environmentof 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

SpringBootIt also provides a way to encapsulate the data in the configuration file into our custom entity class object. The specific operations are as follows:

  • beanLeave the creation of entity classes to Springmanagement.

    @ComponentAdd annotations to the class

  • Use @ConfigurationPropertiesthe annotation to load the configuration file

    prefixYou can also use the attribute in this annotation to specify that only the data with the specified prefix is ​​loaded.

  • BookControllerInject in

The specific code is as follows:

EnterpriseThe 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) +
                '}';
    }
}

BookControllerThe 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
Insert image description here

The solution to this warning is pom.xmlto 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 mysqlonline mysql. This configuration changes the environment configuration to the online environment.

Insert image description here

Modifying configurations back and forth can be troublesome, but SpringBootprovides 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.ymlUse 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 SpringBootwhich configuration to use? You can use the following configuration to enable both configurations

#设置启用的环境
spring:
  profiles:
    active: dev  #表示使用的是开发环境的配置

To sum up, application.ymlthe 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.profilesare obsolete. The latest configuration item used to name is

#开发
spring:
  config:
    activate:
      on-profile: dev

2.4.2 properties file

propertiesTypes of configuration files need to define different configuration files to configure multiple environments.

  • application-dev.propertiesIs the configuration file of the development environment. We configure the port number in this file as80

    server.port=80
    
  • application-test.propertiesIs the configuration file of the test environment. We configure the port number in this file as81

    server.port=81
    
  • application-pro.propertiesIs the configuration file for the production environment. We configure the port number in this file as82

    server.port=82
    

SpringBootOnly the configuration file named will be loaded by default application.properties, so you need to application.propertiesset 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

SpringBootPrograms developed using will be packaged in the future jar, and java -jar xxx.jarservices 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 jara 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 SpringBootprovides jara 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

Insert image description here

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 SpringBootexplained 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
Insert image description here

If multiple methods are used to match the same configuration item, the one with higher priority will take effect.

2.5 Configuration file classification

Insert image description here

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, SpringBootdifferent placement locations of configuration files are defined; and the priorities of placement in different locations are different.

SpringBootIntermediate 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
    Insert image description here

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_filestructureSpringBoot

Insert image description here

resourcesCreate 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 resourcesunder application.ymland 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
Insert image description here

From this result it can be concluded thatConfiguration files under the classpath configtake 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 jarpackages

    Click on the project packageto jarpackage
    Insert image description here

  • jarFind the location of the package on your hard drive
    Insert image description here
    Insert image description here

  • Create a folder where jarthe package is located config, create a configuration file under this folder application.yml, and set the port number in the coordination file to82
    Insert image description here

  • 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
    Insert image description here

    From this result it can be concluded thatconfigConfiguration 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 jarwhere we are located.config

3 SpringBoot integrates junit

Review SpringIntegrationjunit

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class UserServiceTest {
    
    
    
    @Autowired
    private BookService bookService;
    
    @Test
    public void testSave(){
    
    
        bookService.save();
    }
}

Use @RunWithannotations to specify the runner, and use @ContextConfigurationannotations to specify the configuration class or configuration file. The SpringBootintegration junitis particularly simple and can be completed in the following three steps:

  • SpringBootTestAdd annotations to the test class
  • Use to @Autowiredinject 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_testfollowsSpringBoot
Insert image description here

Create an interface com.itheima.serviceunderBookService

public interface BookService {
    
    
    public void save();
}

Create a class in com.itheima.service.implthe package BookServiceImpland make it implement BookServicethe 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/javaCreate a package under com.itheima, create a test class under this package, and BookServiceinject 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 iscom.itheima
  • The package where the test class is located iscom.itheima

If this requirement is not met, you need to @SpringBootTestuse classesthe 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

SpringIntegration Mybatisrequires defining many configuration classes

  • SpringConfigConfiguration class

    • Import JdbcConfigconfiguration class

    • Import MybatisConfigconfiguration class

      @Configuration
      @ComponentScan("com.itheima")
      @PropertySource("classpath:jdbc.properties")
      @Import({
              
              JdbcConfig.class,MyBatisConfig.class})
      public class SpringConfig {
              
              
      }
      
      
  • JdbcConfigConfiguration 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;
        }
    }
    
  • MybatisConfigConfiguration class

    • definitionSqlSessionFactoryBean

    • 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
    Insert image description here

  • Select the technology set to be used by the current module (MyBatis, MySQL)

Insert image description here

4.2.2 Define entity classes

com.itheima.domainDefine the entity class under the package , Bookthe 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.daoDefine the interface under the package , BookDaothe 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/javaDefine the package under com.itheimaand 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 SpringBootbe matched in the configuration file.

application.ymlConfigure 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

Insert image description here

The error message shows that there is no type Springin the container . Why does this happen?BookDaobean

The reason is that Mybatisthe interface will be scanned and the code object that creates the interface will be handed over to Springmanagement, but now it does not tell Mybatiswhich daointerface is it. To solve this problem, we need to BookDaouse it on the interface @Mapper. BookDaoThe interface is improved to

@Mapper
public interface BookDao {
    
    
    @Select("select * from tbl_book where id = #{id}")
    public Book getById(Integer id);
}

Notice:

SpringBootIf 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=UTCor 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. SpringBootThere is a default data source. We can also specify Druidthe data source and follow the following steps to achieve it.

  • Import Druiddependencies

    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.1.16</version>
    </dependency>
    
  • In application.ymlthe configuration file configuration

    You can spring.datasource.typeconfigure what data source to use through . The configuration file content can be improved to

    spring:
      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

SpringBootThis is the end of the study. Next, we will SSMuse the case of integrating the three major frameworks we did during the study SpringBootto 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.

  1. pom.xml

    Configure starting dependencies and necessary resource coordinates (druid)

  2. application.yml

    Set data source, port, etc.

  3. Configuration class

    delete all

  4. dao

    Set up @Mapper

  5. Test class

  6. page

    Place it in the static directory under the resources directory

5.1 Create project

Create SpringBoota project. When creating a project, you need to check web, mysql, mybatisand the project directory structure is as follows
Insert image description here

Since it is used in our project Druid, we need to import Druidthe 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_pagein the project javatogether with the package to springboot_09_ssmthe project, and copy as shown below

Insert image description here

The content that needs to be modified is as follows:

  • Springmvc_11_pageUnder configthe package are configuration classes, and SpringBootthe project does not need these configuration classes, so these can be deleted directly.

  • daoWhen copying the interface under the package to the project, you need to add annotations springboot_09-ssmto the interface.@Mapper

example:
Insert image description here

  • BookServiceTestTesting needs to be changed to SpringBootintegratedjunit

    @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.ymlThe 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

SpringBootThere is no webappdirectory in the program, so SpringBootwhere do static resources need to be placed in the program?

Static resources need to be placed resourcesunder static, as shown in the figure below
Insert image description here

Guess you like

Origin blog.csdn.net/CSDN_Admin0/article/details/131694679