preface

We know that SpringBoot through the configuration class to liberate a bunch of XML file configuration, through the property configuration file, to carry out, system global property configuration, which greatly simplifies our development process, Java Web can also be sweet from now on

Rapid configuration

Properties, Application *. Yaml, and Application *. Yml

Properties > Application *. Yaml > Application *. Yml

That is, add a property configuration to a file such as application.properties or application.yml

You can use the @Value annotation to inject property values into Beans, or use the @ConfigurationProperties annotation to bind property values to structured Beans

The @Value annotation provided by the Spring framework is used to read properties in configuration files and inject them into the corresponding properties of Bean objects one by one. The Spring Boot framework inherits the @Value annotation from the Spring framework by default

  1. inresourcesAdd the application.properties file and configure the corresponding properties
student.name=kenx
student.age=23
Copy the code
  1. The new Java Bean injects the corresponding property into the Java bean and the corresponding field uses the @Value annotation to inject the property Value into the corresponding property.
@Component
@Data
public class User {
    @Value("${student.name}")
    private String name;
    @Value("${student.age}")
    private Integer age;
}
Copy the code

@component adds to the Spring IOC container, @data adds getters, setters

  1. Write use case tests
@SpringBootTest( webEnvironment = SpringBootTest.WebEnvironment.NONE, classes = cn.soboys.kmall.api.ApiApplication.class)
public class PropertiesTest {

    @Autowired
    private User properties;

    @Test
    public void a(a){
        String a= String.format( "student name is %s student age is %s",properties.getName(),properties.getAge()); System.out.println(a); }}Copy the code

I can see that the console is printing normally and data injection is successful

2021-09-08 10:53:02 INFO background-preinit org.hibernate.validator.internal.util.Version HV000001: Hibernate Validator 6.1.7.Final 2021-09-08 10:53:02 INFO Main PropertiesTest Starting PropertiesTest using Java 1.8.0_202 on xiangyongdemacbook-pro. Local with PID 45463 (Started by xiangyong in /Users/xiangyong/selfProject/project/kmall/kmall-api) 2021-09-08 10:53:02 INFO main PropertiesTest The following profiles are active: Test, mptest _ _ | _ _ _ | _ the _ _ _ - | | | | \ / | _) (_ | | | _ \ | _) | | _ | _ \ / | 3.4.1 track the 2021-09-08 10:53:08 INFO main PropertiesTest Started PropertiesTest in 6.132 seconds (JVM running for 7.783) Student name is Kenx student age is 23Copy the code
  1. @ConfigurationPropertiesAnnotations bind attribute values to structured beans

It’s inconvenient to inject at sign Value one by one

@Component
@Data
@ConfigurationProperties(prefix = "student")
public class User {
    private String name;
    private Integer age;
}
Copy the code

This greatly simplifies the code. For structured beans with many properties, it is necessary to specify the prefix via @configurationProperties (prefix = “student”)

Of course, sometimes we need to customize the load property profile using @propertysource

test.id=100
test.name=lucy

Copy the code
package com.lzx.springboot01demo.pojo;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Configuration		// Customize the configuration class
@PropertySource("classpath:test.properties") 	// Specify the location and name of the custom profile
@EnableConfigurationProperties(MyProperties.class)		// Enable the attribute injection function for the corresponding configuration class
@ConfigurationProperties(prefix = "test")		// Specify the config file injection property prefix
public class MyProperties {

    private Integer id;
    private String name;

    // omit getter/setter methods
    // omit the toString() method
}

Copy the code

1. The @Configuration annotation indicates that the current class is a custom Configuration class added as a Component of the Spring container. The traditional @Component annotation can also be used

  1. @ PropertySource (” classpath: test. The properties “) to specify a custom configuration file location and name

  2. @configurationProperties (prefix = “test”) specifies that properties prefixed with test from the configuration file are injected into the properties of the configuration class

  3. @ EnableConfigurationProperties (MyProperties. Class) open the corresponding Configuration attributes of a class into the function, if the Configuration on the class using the @ Component annotation instead of @ the Configuration, @ EnableConfigurationProperties (MyProperties. Class) annotations can be omitted

Application.properties configuration file

Person.id =1Person. family=father,mother # person.family=father,mother # person.family=father,mother Person.map. k1=v1 person.map.k2=v2 # configure object type attribute person.pet.type=dog # configure object name attribute person.pet.name= wealthCopy the code

Application. Y (a)ml Configuration file

  1. Value Indicates a common data type (for example, number, string, Boolean).
server:
  port: 8081
  path: /hello

Copy the code
  1. Value The value can be an array or a single-column collection

There are two main writing methods: indented writing and inline writing; There are two ways to write the indentation:

Written in indent form 1

person:
  hobby:
    - play
    - read
    - sleep
Copy the code

Indented 2

person:
  hobby:
    play,
    read,
    sleep

Copy the code

Inline writing:

person:
  hobby: [play,read,sleep]

Copy the code
  1. Value The value can be Map or object

Indentation

person:
  map:
    k1: v1
    k2: v2

Copy the code

Inline writing:

person:
  map: {k1: v1, k2: v2}

Copy the code

Note that when setting properties using the Spring Boot global configuration file,

If the configured properties are existing properties, such as the service port server.port, Spring Boot scans and reads these configuration properties, overwriting the existing default configurations. If you configure custom properties, you also need to inject these configuration properties into the program for them to take effect

Default property and parameter references

The SpringBoot property configuration file provides us with some unique global property parameter values that we can retrieve directly by default

Using the Spring Boot embedded RandomValuePropertySource random values into class.

Secret =${random. Value} # set random integer my.number=${random. Int} # set random long integer my.bigbumber=${random My.uuid =${random.uuid} # configure integer less than 10 my.number.less. Than. Ten =${random.int(10)} # configure integer in [1024, Range =${random. Int [1024,65536]}Copy the code

We can also reference our own values

App. name=MyApp app.description=${app.name} is a Spring Boot applicationCopy the code