[SpringBoot Usage] SpringBoot (3) configuration file and related tag usage (@ConfigurationProperties/@Value/Environment)

Preface

In the process of using SpringBoot, it is always inevitable to use its related configuration files. We can inject the configuration content through , @ConfigurationPropertiesand @Valuetags applicaiton.properties. It can also be Environmentobtained in real time through objects. The advantages, disadvantages and basics of these usage methods are introduced below. accomplish.


prefix

  • pom.xml
    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <springboot.version>2.3.12.RELEASE</springboot.version>
        <lombock.version>1.18.12</lombock.version>
    </properties>
    
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
        
    </dependencies>

The author uses the father-son Maven project model here. Readers are asked to maintain the relevant versions themselves.

  • application.yml
server:
  port: 8080
  servlet:
    context-path: /arsenal-springboot

config:
  env:
    name: hello
    age: 18

This time we only configure common configuration files. Prefix and other scenarios are not considered.


Label configuration - actual combat

@Value tag
  • Source code definition
package org.springframework.beans.factory.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Value {
    String value();
}

According to @valuethe definition of the label, it can be configured above FIELD// METHOD​​/ .PARAMETERANNOTATION_TYPE

  • Test configuration
package com.yanxml.arsenal.springboot.env.config.value;

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

@Component
@Data
public class StuValue {
    public final static String BEAN_NAME = "StuValue";
    @Value("${config.env.name}")
    private String name;
    @Value("${config.env.age}")
    private Integer age;
}

Binding properties are used here.

  • Test acquisition
@RestController
@RequestMapping(value = "env")
public class EnvController {

    @Autowired
    private StuValue stuValue;
 
    @RequestMapping(value = "stuValue", method = RequestMethod.GET)
    @ResponseBody
    public Object getStuValue(){
        return stuValue;
    }

 }

Insert image description here


@ConfigurationProperties tag
package org.springframework.boot.context.properties;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor;
import org.springframework.stereotype.Indexed;

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Indexed
public @interface ConfigurationProperties {
    @AliasFor("prefix")
    String value() default "";

    @AliasFor("value")
    String prefix() default "";

    boolean ignoreInvalidFields() default false;

    boolean ignoreUnknownFields() default true;
}

  • test case
package com.yanxml.arsenal.springboot.env.config.configuration;

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

@Component
@ConfigurationProperties(prefix = "config.env")
@Data
public class StuConfiguration {
    public final static String BEAN_NAME = "StuConfiguration";
    private String name;
    private Integer age;
}

It is worth noting here that it @ConfigurationPropertiesneeds to @Componentbe used together with labels.

@RestController
@RequestMapping(value = "env")
public class EnvController {
    @Autowired
    private StuConfiguration stuConfiguration;

    @ResponseBody
    @RequestMapping(value = "stuConfiguration", method = RequestMethod.GET)
    public Object getStuConfiguration(){
        return stuConfiguration;
    }

}

Insert image description here


Environment real-time acquisition

If we have seen the loading process of Spring, we can know that when Spring is loading, it obtains the environment variables and related configuration files and puts them into the Environment object. We can obtain each of the objects through methods get().

  • Test Case - StuEnv
package com.yanxml.arsenal.springboot.env.config.environment;

import lombok.Data;

@Data
public class StuEnv {
    public final static String BEAN_NAME = "StuEnv";
    private String name;
    private Integer age;
}

  • Test Case - StuEnvConfig
package com.yanxml.arsenal.springboot.env.config.environment;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

@Component
public class StuEnvConfig {
    @Autowired
    private Environment environment;

    @Bean
    public StuEnv generateStuEnv(){
        StuEnv stuEnv = new StuEnv();
        stuEnv.setName(environment.getProperty("config.env.name"));
        stuEnv.setAge(Integer.valueOf(environment.getProperty("config.env.age")));
        return stuEnv;
    }
}

It is worth noting here that @Beanthe tag modification method needs to be a public type method.

  • Test case - controller
@RestController
@RequestMapping(value = "env")
public class EnvController {
    @Autowired
    private StuEnv stuEnv;


    @RequestMapping(value = "stuEnv", method = RequestMethod.GET)
    @ResponseBody
    public Object getStuEnv(){
        return stuEnv;
    }
}

Insert image description here


Configuration file considerations 1 - prefix


Configuration file considerations 2 - Specification priority of configuration files & how to force specification at runtime


@ConfigurationProperties assembly principle and custom implementation

TODO Stay tuned for the next blog.


Reference

[1] Detailed explanation of the use of @ConfigurationProperties
[2] (Offical)(2.3.12.RELEASE)configuration-metadata-annotation-processor

Guess you like

Origin blog.csdn.net/u010416101/article/details/129116542
Recommended