SpringBook Profile Chapter

Keywords: Java Spring SpringBoot Maven

SpringBoot configuration file defaults to application.properties, but this chapter focuses on yaml file configuration, because the current trend is to use yaml, which is a data description language similar to the subset of standard generic markup language XML, and its syntax is much simpler than XML.

The pom file is posted at the end:

Custom Properties and Loading
We changed the configuration file application.properties from the previous project to application.yml

test:
user:
username : zhangsan
age : 18
toString: the age of ${test.user.username} is ${test.user.age}

Attribute class

package cn.saytime.bean;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class PropertiesConfig {

@Value("${test.user.username}")
private String username;

@Value("${test.user.age}")
private String age;

@Value("${test.user.toString}")
private String toString;

// ... Getter Setter

}

 


Test Controller

package cn.saytime.web;

import cn.saytime.bean.PropertiesConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestController {

@Autowired
private PropertiesConfig propertiesConfig;

@RequestMapping(value = "test", method = RequestMethod.GET)
public String test(){
//    return propertiesConfig.getUsername() + ":" + propertiesConfig.getAge();
return propertiesConfig.getToString();
}
}

Visit http://127.0.0.1/test

Or test unit: Note: Create a new test class under the springboot boot boot boot boot class

package cn.demo;

import java.util.Properties;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import cn.demo.bean.Config;
import cn.demo.bean.Person;
import cn.demo.bean.User;

@RunWith(SpringRunner.class)
@SpringBootTest
public class PropertiesTest {
    
    @Autowired
    private User user;
    
    @Autowired
    private Person person;
    
  //New test.yml and person.yml Documents, not values, are null,But new ones person.properies Values can be taken.
    
    @Test
    public void test() {
        System.out.println("server display name:" + user.getUsername());
        System.out.println("server address:" + user.getAge());
        System.out.println("server emain:" + user.getEmail());
    }
    
    @Test
    public void test2() {
        System.out.println("person-infomation:" + person.toString());
    }
    
    
}

2. Custom Attribute Injection Beans
Inject the test.user in the application.yml file above into the User object. Note that prefix here specifies test.user, which corresponds to the structure in the configuration file.

@Component
@ConfigurationProperties(prefix = "test.user")
public class User {

private String username;

private int age;

public String getUsername() {
return username;
}

// Getter Setter
}
@RestController
public class TestController {

@Autowired
private User user;

@RequestMapping(value = "test2", method = RequestMethod.GET)
public String test2(){
return user.getUsername() + ":" + user.getAge();
}
}

Access http://localhost:8080/test2==> zhangsan:18

 

3. Customize additional configuration files
For example, we don't want to configure some configurations in application.yml/properties. New other configuration files. Here's a new test.yml file. The configuration is the same as the application.yml above. So when we inject objects, we should write this

@Configuration
@PropertySource(value = "classpath:test.yml")
@ConfigurationProperties(prefix = "test.user")
IV. Multiple Environment Profiles
In a real development environment, we need different configuration environments; the format is application-{profile}.properties, where {profile} corresponds to your environment identity, such as:

application-test.properties: test environment
application-dev.properties: development environment
application-prod.properties: production environment
How do you use it? Just add:

spring:
profiles:
active: dev

Because the main entries are application.yml, the configuration file is specified as dev, that is to say, application-dev.yml file is enabled.

Among them, application-dev.yml:

server:
port: 8888

Start the project and find that the port of the program is no longer 8080, but 8888, which means that the development environment is successfully configured.

6. Official Support for Default Profile Properties
http://docs.spring.io/spring-boot/docs/1.5.4.RELEASE/reference/htmlsingle/#common-application-properties

Seventh, Attribute Loading Priority
1. @TestPropertySource annotation
2. Command-line parameters
3. Java System Properties (System.getProperties())
4. Operating system environment variables
5. Only attributes contained in random. * produce a Random Value Property Source
6. Application configuration files (application-{profile}.properties, including YAML and profile variables) outside the packaged jar
7. Application configuration files (application-{profile}.properties, including YAML and profile variables) in the packaged jar
8. The @PropertySource annotation on the @Configuration class
9. Default properties (specified using Spring Application. setDefaultProperties)
That is to say, if I configure a name=zhangsan in my configuration file and type the project as jar, if we use java -jar app.jar --name="Spring" when running, then Spring is injected, with high priority.

Configuration file priority
Looking at the official SpringBook document, you can see that

 

Translation:

A / config subdirectory in the current directory
current directory
A / config package under a classpath
classpath root path
That is, if we have multiple configuration files, such as src/main/resource/application.yml

test:
user:
username : zhangsan
age : 18
toString: the age of ${test.user.username} is ${test.user.age}

name: SpringBoot-root

test2: ${test1}-root

test3: SpringCloud-root

server:
port: 8080
src/main/resource/config/application.yml

test:
user:
username: lisi-config

name: SpringBoot-config

test1: ${name}-config

test4: ${test3}-config

server:
port: 9090

According to the priority, the attributes that can be loaded into SpringBook applications are as follows:

test:
user:
username : lisi
age : 18
toString: the age of lisi is 18

name: SpringBoot-config
test1: SpringBoot-config-config
test2: SpringBoot-config-config-root
test3: SpringCloud-root
test4: SpringCloud-root-config

server:
port: 9090


If you can get the above results, it means you have understood.

Note that when the same attributes exist in the high priority configuration file as those in the low priority configuration file, if the high priority configuration file is selected, the low priority configuration file attributes will also be loaded, rather than only the high priority configuration file attributes.

9. Summary
1. Common custom attributes, using @Value("${xxx}") to inject 2, injecting objects, and using @Configuration Properties (prefix= "test.user")


pom:

<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>cn.demo</groupId>
  <artifactId>springboot_peizhi</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>
  <name>springboot_peizhi</name>
  <url>http://maven.apache.org</url>

  <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
       <version>2.0.4.RELEASE</version>
    </parent>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-api -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.11.2</version>
        </dependency>
        <!-- Spring-Mybatis -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.0</version>
            </dependency>
        <!-- MySQL -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
         </dependency>    
        <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>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
         </dependency>
         <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
         </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                <fork>true</fork>
                </configuration>
            </plugin>
        </plugins>
  </build>
</project>

Posted by cody7 on Sun, 08 Sep 2019 23:51:11 -0700