Part 2: Detailed SpringBoot Configuration

SpringBootIt is a product born to simplify a series of problems such as Springapplication creation, operation, debugging, and deployment.自动装配的特性让我们可以更好的关注业务本身而不是外部的XML配置,我们只需遵循规范,引入相关的依赖就可以轻易的搭建出一个 WEB 工程

The previous article introduced the SpringBootorigin and construction method. Through the tutorial in the first chapter, we SpringBootare unfamiliar with the absence. We can find that SpringBootalthough the XML has been eliminated, it has not achieved zero configuration . It reflects a kind of convention over configuration, also known as press Programming by convention, a software design paradigm, aims to reduce the number of decisions a software developer has to make and gain the benefits of simplicity without losing flexibility. In general, the default configuration is enough to meet the needs of daily development, but in special cases, we often need to use a series of functions such as custom property configuration, custom file configuration, multi-environment configuration, and external command guidance . Don't worry, these SpringBootare all considered for us, we just need to follow its rules to configure

premise

In order to generate data SpringBootbetter , we need to add the following dependencies ( this dependency can be omitted, but there will be no attribute prompts in IDEA and STS, and the configuration without prompts is as hard as writing code with Notepad, so let's take a look The problem will make you cry ), the dependency will only be called at compile time, so don't worry about affecting production...

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

Custom property configuration

application.propertiesWrite the following configuration content in

my1.age=22
my1.name=battcn

Secondly, define the MyProperties1.javafile to map our application.propertiescontent in , so that we can get the content of the configuration file by manipulating the object

package com.battcn.properties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * @author Levin
 * @since 2018/4/23 0023
 */
@Component
@ConfigurationProperties(prefix = "my1")
public class MyProperties1 {

    private int age;
    private String name;
    // 省略 get set

    @Override
    public String toString() {
        return "MyProperties1{" +
                "age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}

The next step is to define our code PropertiesControllerfor injecting MyProperties1and testing the code we wrote. It is worth noting that in the Spring4.xfuture , it is recommended to inject properties in the form of constructors...

import com.battcn.properties.MyProperties1;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author Levin
 * @since 2018/4/23 0023
 */
@RequestMapping("/properties")
@RestController
public class PropertiesController {

    private static final Logger log = LoggerFactory.getLogger(PropertiesController.class);

    private final MyProperties1 myProperties1;

    @Autowired
    public PropertiesController(MyProperties1 myProperties1) {
        this.myProperties1 = myProperties1;
    }

    @GetMapping("/1")
    public MyProperties1 myProperties1() {
        log.info("=================================================================================================");
        log.info(myProperties1.toString());
        log.info("=================================================================================================");
        return myProperties1;
    }
}

Open the browser, enter the following address: http://localhost:8080/properties/1 , observe the console, if the following content is monitored, the program is correct

2018-04-23 15:51:43.145  INFO 15352 --- [nio-8080-exec-2] c.b.controller.PropertiesController      : =================================================================================================
2018-04-23 15:51:43.145  INFO 15352 --- [nio-8080-exec-2] c.b.controller.PropertiesController      : MyProperties1{age=22, name='battcn'}
2018-04-23 15:51:43.145  INFO 15352 --- [nio-8080-exec-2] c.b.controller.PropertiesController      : =================================================================================================

custom file configuration

Define my2.propertiesa , the naming of custom configuration files is not mandatory to applicationstart with

my2.age=22
my2.name=Levin
my2.email[email protected]

Second, define the MyProperties2.javafile , which is used to map our my2.propertiescontent in .

package com.battcn.properties;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

/**
 * @author Levin
 * @since 2018/4/23 0023
 */
@Component
@PropertySource("classpath:my2.properties")
@ConfigurationProperties(prefix = "my2")
public class MyProperties2 {

    private int age;
    private String name;
    private String email;
    // 省略 get set 

    @Override
    public String toString() {
        return "MyProperties2{" +
                "age=" + age +
                ", name='" + name + '\'' +
                ", email='" + email + '\'' +
                '}';
    }
}

Next, use it PropertiesControllerto inject MyProperties2and test the code we wrote

@GetMapping("/2")
public MyProperties2 myProperties2() {
    log.info("=================================================================================================");
    log.info(myProperties2.toString());
    log.info("=================================================================================================");
    return myProperties2;
}

Open the browser, enter the following address: http://localhost:8080/properties/2 , observe the console, if the following content is monitored, the program is correct

2018-04-23 15:59:45.395  INFO 6232 --- [nio-8080-exec-4] c.b.controller.PropertiesController      : =================================================================================================
2018-04-23 15:59:45.395  INFO 6232 --- [nio-8080-exec-4] c.b.controller.PropertiesController      : MyProperties2{age=22, name='Levin', email='[email protected]'}
2018-04-23 15:59:45.395  INFO 6232 --- [nio-8080-exec-4] c.b.controller.PropertiesController      : =================================================================================================

Multi-environment configuration

In real applications, there are often multiple environments ( such as development, testing, production, etc. ), and the database connections in different environments are different. At this time, you need to use spring.profile.activethe powerful functions of . Its format is application-{profile}.properties, here The applicationprefix cannot be changed, it {profile}is defined by ourselves.

Create application-dev.properties, application-test.properties, application-prod.properties, the contents are as follows

application-dev.properties

server.servlet.context-path=/dev

application-test.properties

server.servlet.context-path=/test

application-prod.properties

server.servlet.context-path=/prod

Write in the application.propertiesconfiguration file. spring.profiles.active=devAt this time , it is useless to visit http://localhost:8080/properties/1context-path=/dev , because we set it , so the new path is http://localhost:8080/dev /properties/1 , it can be seen that the property values ​​read by different configurations are different.

external command boot

The first three methods are all based on the configuration file level, so is there any way to guide it externally? Assuming such a scenario, we package and release the code that has been developed. During the period, the test in the test environment passes the test, then it can be released for production. At this time, it is convenient to modify application.propertiesthe configuration or configure it directly in the command parameters . There is no doubt that the latter is more convincing. By default, SpringApplicationcommand-line option arguments (ie: --property, such as --server.port=9000) are added to the Environment, and command-line properties always take precedence over other property sources.

      How to test?

  • Go to the project directory, here is my local directory: F:/battcn-workspace/spring-boot2-learning/chapter2
  • Then open the cmd program, if you will not open cmd in the current directory, please Baidu by yourself, enter:mvn package
  • After packaging, go to: F:/battcn-workspace/spring-boot2-learning/chapter2/target directory, we can find a package named chapter2-0.0.1-SNAPSHOT.jar
  • Then open the cmd program and enter: java -jar chapter2-0.0.1-SNAPSHOT.jar --spring.profiles.active=test --my1.age=32. Carefully observe whether the key values spring.profiles.active=test​​ofmy1.age=32 these two configurations are familiar (if you don't know it, please read it carefully from the beginning)
  • Finally enter the test address: http://localhost:8080/test/properties/1 We can find {"age":32,"name":"battcn"}that correct

Summarize

  • Master @ConfigurationPropertiesthe @PropertySourceusage and function of annotations
  • Mastering Writing Custom Configurations
  • Master the way external commands guide configuration

At present, many big guys have SpringBootwritten tutorials about . If there are any similarities, please bear with me. This tutorial is based on the latest . spring-boot-starter-parent:2.0.1.RELEASEThe features of the new version will be introduced together…

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324922460&siteId=291194637