Recently I learned about Spring Boot and wrote a simple project with it, and really found it to be a great boon for people who use Spring to develop without having to configure as much as before. This article, combined with some common interview questions and development will be used, Spring Boot to summarize.

What is Spring Boot

Spring Boot is a framework that allows you to quickly start Spring. It takes the principle of “convention over configuration” and provides a lot of automatic configuration without having to write template-based configuration files. You can quickly create a Spring project that can run on its own.

In addition to the auto-configuration feature, it has the following features:

The starter starter

It provides a number of framework starter initiators to simplify Dependency management for Maven. In Spring projects, when importing dependencies from other frameworks, you also need to import dependencies from other frameworks, which can be difficult to manage if there are many frameworks. Spring Boot provides various starter initiators to manage Spring Boot. For example, after the spring-boot-starter-web dependency is imported, the following dependencies are automatically added:

Embedded Servlet container

It has a number of Servlet containers embedded, Tomcat, Jetty, and more. In this way, there is no need to download Tomcat first, set up the running environment, and then deploy in the form of war package. Instead, it can directly run independently in the form of JAR package through Java-jar xxx.jar.

Application monitoring of quasi-production environment

Provides application monitoring for quasi – production environment. Runtime projects can be monitored based on HTTP, JMX, SSH, and so on. The Actuator is not well understood and will be supplemented later.

Spring, SpringBoot, and SpringCloud

Many of you have heard of these three things, but what’s the difference between them?

Spring is a one-stop lightweight open source framework for JavaSE/EE. Many modules are provided, such as IoC, AOP, MVC, Test, and so on. SpringMVC is just one module.

SpringBoot is a Boot initiator based on Spring, in order to build a Spring project easier and faster. This is for monomer applications.

SpringCloud is a comprehensive solution under the micro-service architecture, which manages each service developed with SpringBoot. It integrates many basic components to solve the problems such as configuration management, service governance, fault tolerance and so on brought by business separation.

3. Boot mode of Spring Boot

There are three main Boot modes for Spring Boot.

1. Create a JAR package

The Serlvet container is built into Spring Boot and can be used directly with java-jar xxx.jar. This is now recommended. This way, you can also specify some parameters at run time.

After introducing the spring-boot-Maven-plugin in the POP.xml file:

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
Copy the code

You can execute the MVN clean package command to package it into a JAR package, which can then be run through the jar-jar xxx.jar command.

2. Run the main method

Spring Boot projects always have a main class that can be launched by running the main method of that class. This applies to development and debugging.

3. Pack it into a WAR bag

For web projects, you can also create a WAR package and use an external Tomcat container.

4. Configuration files

Spring Boot offers a range of automated configurations to simplify heavy configuration. But we also need to understand how to modify these default configurations to accommodate specific scenarios.

4.1 Configuration Modes

Currently, Spring Boot supports two configuration methods. One is the traditional properties file, which is represented by key=value. For example, to change the default port:

server.port=8081
Copy the code

The other is the YAML file that is currently recommended. It is expressed in indented form to make the structure more legible. Such as:

server:
  port: 8081
Copy the code

In addition, YAML files also support the ability to define the configuration of multiple different environments in the same file through the spring.profiles property. For example, in the following file:

server:
  port: 8080
---
server:
  port: 8081
spring:
  profiles: prod
--- 
server:
  port: 8082
spring:
  profiles: test
Copy the code

If we specify the test environment, server.port uses port 8082; If the proD environment is specified, port 8081 is used; otherwise, port 8080 is used.

However, the YAML file has some shortcomings in that it cannot load the specified YAML configuration file via the @propertysource annotation. But you can annotate it with @Value.

For more details on YAML syntax, see: Yifeng Ruan: YAML Language Tutorial

4.2 Configuring the Read Mode

For custom configurations to be applied to our project, SpringBoot currently supports two reading methods. They also support working with @propertysource to specify the configuration file to use.

1. @Value

One is the @value that I just mentioned, which reads the configuration to a specific property.

For example, add the following configuration to the application.yml file:

user:
  name: TimberLiu
  age: 21
  address: China
Copy the code

The User class can be read as follows:

@Component
@Setter
@Getter
public class User {
    @Value("${user.name}")
    public String name;
    
    @Value("${user.age}")
    public int age;
    
    @Value("${user.address}")
    public String address;
}
Copy the code

2. @ConfigurationProperties

The other is @ConfigurationProperties, which reads the configuration onto the class.

Using @configurationProperties, you can configure the same configuration as the following:

@Component
@Setter
@Getter
@ConfigurationProperites(prefix="user")
public class User {

    public String name;
    public Integer age;
    public String address;
}
Copy the code

3. Differences between the two

So what’s the difference between these two approaches? Take a look at the chart below:

/ @ConfigurationProperties @Value
function Read the configuration onto the class Read configuration to properties
Loosely bound support Does not support
JSR303 data verification support Does not support
Complex type encapsulation support Does not support

Here is an example, for example, for the following configuration:

person:
  name: timberliu
  age: 21
  birthday: 2019/ 4/17
  info: {k1: v1,k2: v2}
  lists:
    - jack
    - rose
  dog:
    last_name: wang Last_name matches lastName, loosely bound
    age: 3
Copy the code

Using @configurationProperties, you can configure:

@Component
@Getter
@Setter
@ConfigurationProperties("person")
@Validated
public class Person {
    // Non-null check
    @NotNull
    private String name;
    private Integer age;
    // Date type, data verification
    @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
    private Date birthday;
    // Complex type
    private Map<String, String> info;
    private List<Object> lists;
    private Dog dog;
}

@Component
@Getter
@Setter
@ConfigurationProperties("person.dog")
public class Dog {

    private String lastName;
    private Integer age;
}
Copy the code

4.3 Configuring multiple Environments

Generally, projects use different configurations for different environments. In Spring Boot, the file name of a multi-environment configuration must meet the format of application-{profile}. Properties or.

As to which environment will be loaded, this needs to be set in the application.properties file via the spring.profiles.active property.

For example, if there are configuration files for three environments:

application-dev.properties
application-test.properties
application-prod.properties
Copy the code

Specifying spring.profiles.active=dev in the application.properties file loads the contents of the application-dev.properties configuration file.

In actual development, the configuration roadmap for multiple environments is as follows:

  • inapplication.propertiesConfigure some common properties in the file and setspring.profiles.active=devIs configured as the development environment by default.
  • inapplication-{profile}.propertiesFile to configure the content of different environments.
  • You can use the COMMAND line interface (CLI) to deactivate the configuration of the specific environment.

4.4 Configuring the Loading Sequence

Properties or application-{profile}.properties files, on the command line, and so on. So in order to overwrite the values of each attribute more reasonably, let’s look at the loading order of these configurations. Since there are so many loading sequences, here are just a few common ones:

  • Parameter specified on the command line. For example,java -jar myapplication.jar --server.port=8081.
  • JavaSystem variables.
  • throughrandom.*Random properties configured.
  • JaroutsidePart of, for different{profile}Configuration file contents for the environment, for exampleapplication-{profile}.properties.
  • JarWithin thePart of, for different{profile}Configuration file contents for the environment, for exampleapplication-{profile}.yml.
  • JaroutsideThe department ofapplication.propertiesapplication.yml.
  • JarWithin theThe department ofapplication.propertiesapplication.yml.
  • In custom@ConfigurationClass, pass@PropetySourceAttributes defined by annotations.
  • useSpringApplication.setDefaultPropertiesAttributes defined.

The lower the load order, the lower the priority.

Five, the last

This article introduced the basic concepts of Spring Boot. The SpringBoot configuration file is described in detail, such as the format of the configuration file, the way to read it, how to configure it in multiple environments, and the loading sequence of the configuration file.

The next article will detail how SpringBoot starts and how it is automatically configured.