Spring Boot Tutorial (3): Configuration File

1. External arrangement

Spring Boot allows you to externalize your configuration so that you can use the same code in different environments. You can externalize configuration using properties files, YAML files, environment variables and command line arguments. Using the @Value annotation, property values ​​can be injected directly into your beans and accessed through Spring's Environment abstraction or by binding to structured objects.

Spring Boot uses a very specific order of PropertySources to allow reasonable overriding of values, properties need to be considered in the following order:

  1. Develop Devtools global settings properties on the home directory ( ~/.spring-boot-devtools.propertieswhen devtools is active).
  2. @TestPropertySourceAnnotation in your test.
  3. @SpringBootTest#propertiesAnnotation property in your test.
  4. command line arguments
  5. Dependent properties SPRING_APPLICATION_JSON(inline JSON embedded in environment variables or system properties).
  6. ServletConfigInitialization parameters.
  7. ServletContextInitialization parameters.
  8. java:comp/envJNDI properties from
  9. Java System Properties ( System.getProperties())
  10. operating system environment variables
  11. Only random.*properties contained within will produce aRandomValuePropertySource
  12. Application configuration files ( application-{profile}.propertiesand YAML variants) outside the packaged jar
  13. Application configuration file ( application-{profile}.propertiesand YAML variant) inside the packaged jar
  14. Application configuration file ( application.properties, containing YAML and profile variables) outside the packaged jar
  15. Application configuration file ( application.properties, containing YAML and profile variables) inside the packaged jar
  16. Annotations on @Configurationclasses@PropertySource
  17. Default properties (use SpringApplication.setDefaultPropertiesspecified)

In Spring Boot, the original XML configuration content when integrating Spring applications was replaced by the introduction of modular Starter POMs in pom.xml. Each module has its own default configuration, so if it is not a special application scenario, only You need to complete some property configuration in application.properties to start the application of each module.

2. Custom properties

Use @Value() annotation method

1. application.propertiesAdd custom properties. ${}Other configuration properties in the configuration file can also be obtained by getting the file

# 修改服务端口号
server.port=8888

# 自定义属性
pocket.name=蝈蝈
pocket.age=26
pocket.county=长宁区
# 配置文件也可以通过${}引用其他变量
pocket.address=上海市${pocket.county}

@Value()2. Get custom attributes through annotations

package com.songguoliang.properties.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Description 通过@Value使用自定义属性
 * @Author sgl
 * @Date 2018-04-27 14:41
 */
@RestController
public class HelloController {
    /**
     * 通过${}获取application.properties里的自定义属性
     */
    @Value("${pocket.name}")
    private String name;

    @Value("${pocket.age}")
    private Integer age;

    @Value("${pocket.address}")
    private String address;

    @GetMapping("/hello")
    public String hello() {
        return "大家好,我的名字是" + name + ",我今年" + age + "岁了,我在" + address+"工作!";
    }
}

3. Restart the service, enter the browser: http://localhost:8888/hello, you can see the following:
write picture description here

If Chinese garbled characters appear: refer to SpringBoot custom properties garbled characters

use prefix

Spring Boot supports objects that automatically encapsulate properties through prefixes, which is very suitable for situations where there are many properties. In fact, this method is also used to obtain custom properties in various starters, such as http encoding-related configuration prefixes spring.http.encoding(refer to org.springframework.boot.autoconfigure.http.HttpEncodingProperties)

@ConfigurationProperties1. Specify the entity prefix through annotations , as follows:
Create entity class User:

package com.songguoliang.properties.model;

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

/**
 * @Description 由Spring根据ConfigurationProperties自动注入属性的值
 * @Author sgl
 * @Date 2018-04-27 15:29
 */
@Component
@ConfigurationProperties(prefix = "pocket")
public class User {
    private String name;
    private Integer age;
    private String address;

    //省略了get、set方法
}

2. Add Action for page access:

package com.songguoliang.properties.controller;

import com.songguoliang.properties.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Description
 * @Author sgl
 * @Date 2018-04-27 15:31
 */
@RestController
public class ModelController {
    /**
     * 注入user
     */
    @Autowired
    private User user;

    @GetMapping("/say")
    public String hello() {
        return "大家好,我的名字是" + user.getName() + ",我今年" + user.getAge() + "岁了,我在" + user.getAddress() + "工作!";
    }
}

3. Restart the service, enter the browser http://localhost:8888/say, you can see:
write picture description here

random number

In the configuration file, you can also call the RandomValuePropertySource#getRandomValue(String type) method through random.* to generate a value randomly. Note: the random key cannot start with random, such as random.a is problematic

1. Add the following configuration to the configuration file:

# 随机数
# 随机int
test.randomInt=${random.int}
# 随机10以内
test.randomIntMax=${random.int(10)}
# 随机20-50
test.randomIntMiddle=${random.int(20,50)}
# 随机Long
test.randomLong=${random.long}
# 字符串
test.randomValue=${random.value}
# uuid
test.randomUuid=${random.uuid}

# key不能random开头,使用时会有问题
#random.num=${random.int}

2. Create the RandomData entity class:

package com.songguoliang.properties.model;

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

/**
 * @Description
 * @Author sgl
 * @Date 2018-04-27 15:50
 */
@Component
@ConfigurationProperties(prefix = "test")
public class RandomData {
    private Integer randomInt;
    private Integer randomIntMax;
    private Integer randomIntMiddle;
    private Long randomLong;
    private String randomValue;
    private String randomUuid;

    //省略get、set方法
}

3. Add a method to the ModelController class:

@Autowired
private RandomData randomData;

@GetMapping("/random")
public RandomData random() {
    return randomData;
}

4. The browser input: http://localhost:8888/random, the browser sees:
write picture description here

custom configuration file

Although application.properties can also define non-starter configuration, that is, define your own configuration, if you put your own configuration in this file, it may make the file very bloated, you can put your own configuration in other property files, so that Configuration is more centralized

1. Create a test.properties file in the root directory of resources

test.name=测试自定义配置文件
test.num=123

2. Create a TestEntity entity:

package com.songguoliang.properties.model;

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

/**
 * @Description
 * @Author sgl
 * @Date 2018-04-27 17:01
 */
@ConfigurationProperties("test")
@Component
@PropertySource("classpath:test.properties")
public class TestEntity {
    private String name;
    private Integer num;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getNum() {
        return num;
    }

    public void setNum(Integer num) {
        this.num = num;
    }
}

3. Add url mapping to ModelController:

@Autowired
private TestEntity testEntity;

@GetMapping("/test")
public TestEntity getTestEntity() {
    return testEntity;
}

4. Browser input: http://localhost:8888/test, see:
write picture description here





Source code:
github
code cloud

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326635652&siteId=291194637