Two configuration files in SpringBoot

  • There are two ways to write the SpringBoot global configuration file andThe profile name is fixed, The configuration file is mainly used to modify the default value of SpringBoot automatic configuration.
  • Configuration file src/main/resourcesdirectory path the class or /configthe

一、application.properties

Grammatical structure: key=value

server.port=8080

二 、 application.yml

Grammatical structures:

key:
	value

yml is a file in YAML (YAML Ain't Markup Language) language,Data-
centric
, More suitable for configuration files than json, xml, etc. Most of the previous configuration files are configured using xml; for example, a simple port configuration, let's compare yml and xml;

Traditional xml configuration:

<server>
    <port>8081<port>
</server>

yaml configuration: (more concise, more prominent data)

server:
  prot: 8080

1. Basic grammar of yaml

  • Indentation is used to control the hierarchical relationship, as long as the column of data aligned on the left is at the same level.

  • The case of attributes and values ​​is very sensitive.

  • The Tab key is not allowed when indenting, only spaces are allowed, and the number of spaces for indentation is not important.

  • A space should be followed by the colon to separate the key value.

2. Three data structures supported by yaml:

  • Object: a collection of key-value pairs
  • Array: a set of values ​​in order
  • Literal: a single, indivisible value

(1) Object (or Map key-value pair)

#对象、Map格式
k: 
    v1:
    v2:

Pay attention to the indentation of the relationship between the attributes and worth of the object;

student:
    name: lisi
    age: 3

Write in one line:

student: {
    
    name: lisi,age: 3}

(2) Array (or List, set)

A -represents an element in the array, such as the value of:

pets:
 - cat
 - dog
 - pig

Write in one line:

pets: [cat,dog,pig]

(3) Literal
number, string, Boolean, date

String

  • Do not use quotes by default
  • You can use single or double quotes, single quotes will escape special characters
  • “ ”Double quotation marks will not escape special characters in the string; for
    example: name: “kuang \n shen” Output: kuan, newline shen
  • ''Single quotes will escape special characters. For
    example: name:'kuang \n shen' output: kuang \n shen

(4) separate documents
a plurality of documents with - - -spaced

Three, configuration file value injection

application.yml :

person:
  name: lisi
  age: 3
  happy: false
  birth: 2000/01/01
  maps: {
    
    k1: v1,k2: v2}
  lists:
   - code
   - girl
   - music
  dog:
    name: 旺财
    age: 1

There are two ways to inject configuration file values, @Value and @ConfigurationProperties.

(1)@Value

@Component 
public class Person {
    
    
	@Value("${person.name}")
    private String name;
    @Value("#{11*2}")
    private Integer age;
    @Value("true")
    private Boolean happy;
}

(2) @ConfigurationProperties injects properties into the entity class

@Component 
@ConfigurationProperties(prefix = "person")
public class Person {
    
    
    private String name;
    private Integer age;
    private Boolean happy;
    private Date birth;
    private Map<String,Object> maps;
    private List<Object> lists;
    private Dog dog;
}

@ConfigurationProperties: Map the value of each attribute configured in the configuration file to this component; tell SpringBoot to bind all the attributes in this class to the related configuration in the configuration file. Parameter prefix = "person": change the configuration file All the attributes under person correspond one to one.

Need to import:

<!-- 导入配置文件处理器,配置文件进行绑定就会有提示,需要重启 -->
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-configuration-processor</artifactId>
  <optional>true</optional>
</dependency>

(3) The difference between @Value and @ConfigurationProperties:

@ConfigurationProperties @Value
Features Batch injection of properties of configuration files Inject one by one
Loosely bound stand by not support
Game not support stand by
JSR303 check stand by not support
Complex type package stand by not support

1) Loose binding:
If a property of person in the configuration file is firstName, then loose binding means that when using @ConfigurationProperties to inject properties, the following methods are equivalent:

person.firstName:
person.first-name:
person.first_name:
PERSON_FIRST_NAME:

2)
SpEL : @Value supports spring's expression language:

    @Value("#{11*2}")
    private Integer age;

3) JSR303 verification
support JSR303 data verification when using @ConfigurationProperties, use @Validated annotation

@Component 
@Validated
@ConfigurationProperties(prefix = "person")
public class Person {
    
    
	@Email   //name必须是邮箱格式
    private String name;
}

4) Complex type packaging

@Component 
public class Person {
    
    
	@Value("${person.maps}")
    private Map<String,Object> maps;
}

For the above, using @Value to inject a complex type of value will cause an error.

note:

  • If we specially write a JavaBean to map one-to-one with the configuration file, use @configurationProperties directly
  • If you only need to use a value in the configuration file in your application, just use @Value directly.

(4)@PropertySource

  • Can be used @PropertySource, load the specified configuration file,Can only be used for properties files
@PropertySource(value = "classpath:person.properties")
  • @configurationProperties: Get the value from the global configuration file by default;
@ConfigurationProperties(prefix = "person")

(5)@ImportResource

Import the Spring configuration file and let the content take effect.

@SpringBootApplication

@ImportResource(locations={
    
    "classpath:beans.xml"})

public class HellospringbootApplication {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(HellospringbootApplication.class, args);
    }
}

Four, configuration file placeholder

The configuration file can also write placeholders to ${}generate random numbers,

person:
    name: lisi${
    
    random.uuid} # 随机uuid
    age: ${
    
    random.int}  # 随机int
    happy: false
    birth: 2000/01/01
    maps: {
    
    k1: v1,k2: v2}
    hello: hello
    lists:
      - code
      - girl
      - music
    dog:
      name: ${
    
    person.hello:other}_旺财
      age: 1

name: ${person.hello:other}_旺财: If person.hello exists, output: the value corresponding to hello, if not, output othor. Here the colon specifies the default value.

Five, Profile

Profile is Spring's support for different configuration functions for different environments. It can quickly switch environments by activating and specifying parameters.

(1) Multi-profile file format:

format:application-{profile}.properties/yml:

E.g:

  • application-dev.properties //Development environment
  • application-test.properties //Test environment
  • application-prod.properties //production environment

Application.properties default configuration, if you need to activate an environment in the default configuration file application-{profile}.properties/ymlconfigurationspring.profiles.active=dev

(2) Document block mode of yml

server:
  port: 8081
spring:
  profiles:
    active: dev  
---
server:
  port: 8082
spring:
  profiles: dev
---
server:
  port: 8083
spring:
  profiles: prod

(3) Command line mode

1) At startup, specify the configuration file.
Insert picture description here

2) Specify the configuration file when running in -jar mode

java -jar springBoot.jar --spring.profiles.active=prod

(4) Virtual machine parameter configuration

Insert picture description here

Six, configuration file loading location

1. The default loading location of the configuration file


Spring Boot startup will scan the application.properties or application.yml files in the following locations as the default configuration files for Spring boot.

  • file:./config/
  • file:./
  • classpath:/config/
  • classpath:/

The above is in the order of priority from high to low. High-priority configuration content will override low-priority configuration content, and the content of each configuration file will be complementary (all configuration files in the above position will be loaded).
Insert picture description here
note:

  • 1, 2 belong to the configuration files under the project package, they will not be packaged in the jar package, the jar package file will only contain the configuration files 3 and 4 under the classpath.

2. Loading of external configuration files

(1) After the project is packaged, we can also use command line parameters spring.config.locationto change the default configuration.

java -jar springboot.jar --spring.config.location=C:/application.properties

(2) Command line parameters: When there are multiple parameters, they can be separated by spaces.

java -jar springboot.jar --server.port=8095

(3) You can also write configuration files outside the jar package:
Insert picture description here

  • Application-{profile}.properties or application.yml (with spring.profile) configuration file outside the jar package
  • The application-{profile}.properties or application.yml (with spring.profile) configuration file inside the jar package
  • Application.properties or application.yml (without spring.profile) configuration file outside the jar package
  • The application.properties or application.yml (without spring.profile) configuration file inside the jar package

Guess you like

Origin blog.csdn.net/glpghz/article/details/108400644