Spring Boot Global Profile

2.1.5 Global Profile

The global profile can modify some default configuration values.Spring Boot uses oneApplication.propertiesorApplication.yml/applicationThe.Yaml file acts as a global configuration file and is placed in the [src/main/resources] directory or in the [config] of the class path.

Typically placed in the resources directory.

We can do this atApplication.properties/Application.ymlA file defines Spring Boot properties that define items, whether they are system properties, environment variables, command parameters, or custom profile names and locations.

# Specify project run port
server.port=8080
# Specify project application context path
server.servlet.context-path=/learn
# Specify project name
spring.application.name=learn
2.1.5.1 Configuration Autoprompt

When writing configurations, since the Person object properties we configure are customized, Spring Boot cannot automatically recognize them, and there will be no property prompts.In practical development, for the sake of configuring easily with code prompts, you can use the @ConfigurationProperties annotation for profile property injectionPom.xmlAdd the configuration processing dependencies provided by Spring Boot to the file.

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

After adding the configuration, the project needs to be recompiled and run to take effect.

2.1.5.2 Presentation Preparation

First prepare two entity classes: Pet, Person, and passApplication.propertiesandApplication.ymlCustom configuration properties from the configuration file are injected into the Person entity class

@Data
public class Pet {
    private String type;
    private String name;
}
@Data
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
    private int id; // id
    private String name; // Name
    private List hobby; // hobby
    private String[] family; // Member of family
    private Map map;
    private Pet pet; // Pets
}

The @ConfigurationProperties(prefix = "person") comment injects property values in the configuration file that start with person into the entity class through the setXXX() method

The @Component annotation is used to place Person class objects currently injected with property values as Bean components in the Spring container so that they can be assigned to @ConfigurationProperties

2.1.5.3 application.properties
person.id=1
person.name=Zhang San
person.hobby=Having dinner,Sleep,Bean Bean
person.family=father,mother
person.map.k1=v1
person.map.k3=v2
person.pet.type=cat
person.pet.name=Hemp flowers

Test Class

// Test the startup class and load the Spring Boot test notes
@RunWith(SpringRunner.class)
// Mark as Spring Boot unit test class and load the project's ApplicationContext context
// classes knows the project master startup class
@SpringBootTest(classes = LearnApplication.class)
public class LearnApplicationTest {

    @Autowired
    private Person person;

    @Test
    public void testProperties() {
        System.out.println(person);
    }

}

Print results

Person(id=1, name=Zhang San, hobby=[eat, sleep, beans], family=[father, mother], map={k1=v1, k3=v2}, pet=Pet(type=cat, name=spaghetti))

As you can see, the Person object is printed correctly, explainingApplication.propertiesConfiguration file properties are configured correctly, and property injection is automatically completed with relevant annotations.

2.1.5.4 application.yaml

Yaml file format is a JSON superset file format supported by Spring Boot. Compared with traditional properties configuration file, yaml file is a more intuitive and easily recognized data serialization format with data as the core.Application.yamlWorking principle and configuration fileApplication.propertiesSame, but the yaml format profile looks simpler.

  • The yaml file looks like the extension can be.Yaml or.yml
  • Application.ymlThe file configures attributes in key:(space) value format and controls hierarchical relationships with indentation

Different formats for different data types

  • value values are common data types (numbers, strings, Booleans, and so on)

    server:
    port: 8081
    spring:
    application:
      name: demo
  • value values are arrays and single-column collections

    There are two main writing styles: indentation and inline

    • Indentation
    person:
      hobby:
        - Having dinner
        - Sleep
        - Bean Bean

    or

    person:
      hobby:
        Having dinner,
        Sleep,
        Bean Bean
    • Inline writing
    person:
      hobby: [Having dinner,Sleep,Bean Bean]

    or

    person:
      hobby: Having dinner,Sleep,Bean Bean
  • value values are Map collections and objects

    There are two main writing styles: indentation and inline

    • Indentation
    person:
      map:
        k1: v1
        k2: v2
    • Inline writing
    person:
      map: {k1: v1-1,k2: v2-2}

test

Create under ResourcesApplication.yml

person:
  id: 1
  name: Roger
  hobby: [Having dinner,Sleep,Bean Bean]
  family: father,mother
  map: {k1: v1-1,k2: v2-2}
  pet:
    type: cat
    name: Hemp flowers

Test Class

// Test the startup class and load the Spring Boot test notes
@RunWith(SpringRunner.class)
// Mark as Spring Boot unit test class and load the project's ApplicationContext context
// classes knows the project master startup class
@SpringBootTest(classes = LearnApplication.class)
public class LearnApplicationTest {

    @Autowired
    private Person person;

    @Test
    public void testProperties() {
        System.out.println(person);
    }

}

Print results

Person(id=1, name=Zhang San, hobby=[eat, sleep, beans], family=[father, mother], map={k1=v1, k3=v2}, pet=Pet(type=cat, name=spaghetti))

As you can see, the Person object is printed correctly, explainingApplication.ymlConfiguration file properties are configured correctly, and property injection is automatically completed with relevant annotations.

2.1.5.5 Profile Property Value Injection

When using Spring Boot for global profile settings:

  • If the configured property is a Spring Boot already existing property, such as a service portServer.portSpring Boot automatically scans and reads the property values in these profiles and overrides them by default.
  • If the configured properties are user-defined properties, such as Person entity class properties that have just been customized, they must also be injected into the program to take effect.

Spring Boot supports multiple ways of injecting profile properties, @ConfigurationProperties and @Value

2.1.5.5.1 @ConfigurationProperties

Spring Boot provides the @ConfigurationProperties annotation to quickly and easily bulk inject custom properties from a configuration file into multiple properties of a Bean object.

as

@Data
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
    private int id; // id
    private String name; // Name
    private List hobby; // hobby
    private String[] family; // Member of family
    private Map map;
    private Pet pet; // Pets
}

The above code maps each property in the configuration file to a Person class component using @Component and @ConfigurationProperties(prefix = "person").

2.1.5.5.2 @Value

The @Value is provided by the Spring framework to read property values in the configuration file and inject them one by one into the corresponding properties of the Bean object. Spring Boot inherits the @Value annotation from the Spring framework by default, so it can also be used to read and inject profile property values in the Spring Boot framework.

as

@Data
@Component
public class People {
    @Value("${people.id}")
    private Integer id;
    @Value("${people.name}")
    private String name;
}
people:
  id: 1
  name: Li Si

test result

People(id=1, name=Li Si)

You can see that the attribute values are printed correctly and can be injected through @Value.

Notes for using the @Value annotation

  • If @Value is used, the corresponding property is configured in the configuration file or the default value is set, otherwise an exception will occur

    Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'people.name' in value "${people.name}"

    Example of how default values are set

    @Data
    @Component
    public class People {
      @Value("${people.id:10}")
      private Integer id;
      @Value("${people.flag:true}")
      private Boolean flag;
      // Set default value to empty string
      @Value("${people.name:}")
      private String name;
      // Set default value to null
      @Value("${people.remark:#{null}}")
      private String remark;
    }
  • The @Value annotation does not support property injection for Map collections, objects, and profiles written inline in the yml file format, if an assignment error occurs

    Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'people.name' in value "${people.name}"

2.1.6 Custom Configuration

Spring Boot exempts most of the manual configurations in the project. For some specific cases, we can modify the global configuration file to suit the specific build environment, so to speak, almost all configurations can be written inApplication.propertiesIn the configuration file, Spring Boot automatically loads the global configuration file to avoid the hassle of loading manually.

However, if we customize the configuration files, Spring Boot does not recognize them and we need to load them manually at this time.

2.1.6.1 @PropertySource

The @PropertySource annotation can be combined with the @Component annotation to accommodate this requirement for loading custom configuration files.

The @PropertySource annotation is used to specify the specific location and name of the custom configuration file, and @Component needs to be added to the class to ensure that Spring Boot can scan the annotation, indicating that the class is handed over to the Spring container for maintenance.

Of course, for property values injected into the corresponding class property values in a custom configuration file, you can use the @ConfigurationProperties or @Value annotation for property value injection

Example

  1. EstablishTest.properties

    test.id=1
    test.name=zhangsan
  2. Create Configuration Class

    @Data
    @Component
    // Introducing the name and location of a custom profile
    @PropertySource(value = "classpath:test.properties", encoding = "UTF-8")
    @ConfigurationProperties(prefix = "test")
    public class MyProperties {
       private int id;
       private String name;
    }
  3. test

    // Test Launcher and load Spring boot test notes
    @RunWith(SpringRunner.class)
    // Mark this class as a Spring boot unit test class and load the project's ApplicationContext context
    @SpringBootTest
    class SpringbootDemoApplicationTests {
       @Autowired
       private MyProperties myProperties;
       @Test
       void contextLoads() {
           System.out.println(myProperties);
       }
    }

2.1.6.2 @Configuration

In the Spring Boot framework, configuring and components in containers using configuration classes is recommended

In the Spring Boot framework, a configuration class is usually defined with the @Configuration annotation, and Spring Boot automatically scans and identifies the configuration class, replacing the XML configuration file in the traditional Spring framework.

When you define a configuration class, you also need to configure the component using the @Bean annotation on the methods in the class, inject the method's return object into the Spring container, and the component name defaults to the method name. You can also customize the name of the component using the @Bean annotation name, value property.

  1. Create Config Configuration Class

    // Mark this class as a configuration class
    @Configuration
    public class MyConfig {
       @Bean // Add the return value object as a component to the Spring container with the identity ID defaulting to the method name or custom @Bean(id)
       public MyService myService() {
           return new MyService();
       }
    }
  2. test

    // Test Launcher and load Spring boot test notes
    @RunWith(SpringRunner.class)
    // Mark this class as a Spring boot unit test class and load the project's ApplicationContext context
    @SpringBootTest
    class SpringbootDemoApplicationTests {
       @Autowired
       private ApplicationContext applicationContext;
       @Test
       void contextLoads() {
           boolean myService = applicationContext.containsBean("myService");
           System.out.println(myService);
       }
    }

2.1.7 Random Number Settings

In the Spring Boot configuration file, random value settings use the Spring Boot embedded Random ValuePropertySource class to inject random values into some cryptic or test case property values

The syntax format for random values is ${random.xx}, the XX identity needs to specify the type and range of random numbers generated, which can be integers, uuid s, or strings

@Data
@Component
@ConfigurationProperties(prefix = "myr")
public class MyRandom {

    private String secret; // Configure Random Values
    private Integer number; // Configure random integers
    private Long bignumber; // Configure Random Long Type Integers
    private String uuid; // Configure random uuid
    private int lessthanten; // Random integers configured under 10
    private int range; // Random integers with configuration range between [1024,5048]

}
myr:
  secret: ${random.value}   # Configure Random Values
  number: ${random.int}     # Configure random integers
  bignumber: ${random.long} # Configure Random Long Type Integers
  uuid: ${random.uuid}      # Configure random uuid
  lessthanten: ${random.int(10)}  # Random integers configured under 10
  range: ${random.int[1024,5048]} # Random integers with configuration range between [1024,5048]

References between 2.1.8 parameters

In the SpringBoot configuration file, the property values of the configuration file can also be referenced between parameters, that is, to reference more previously defined properties in the property values of the later configuration, so that the property values can be resolved directly.

Syntax format for reference between parameters: ${xxx}, XXX denotes a property name that has been previously configured in the configuration file

Benefits: Multiple references, one configuration

@Data
@Component
@ConfigurationProperties(prefix = "app")
public class App {
    private String name;
    private String describe;
}
app:
  name: test APP
  describe: ${app.name}Is used to test

Tags: Web Development Spring Java JSON Attribute

Posted on Mon, 15 Jun 2020 18:19:02 -0400 by MtPHP2