preface

Even now with simplified configuration, a separate configuration file is always easy to understand and reassuring. By default, Spring creates an application.properties file in the Resources folder after building the project, as does application.yml. @ConfigurationProperties takes the data from the configuration file and injects it into the class.

The source code

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

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

    boolean ignoreInvalidFields(a) default false;

    boolean ignoreUnknownFields(a) default true;
}
Copy the code

use

Pass the prefix name from the configuration file to the annotation if the configuration file looks like this:

myConfigs:
  config1:
    field1: f1
    field2: f2
    field3: f3
Copy the code

The configuration class in your code should look like this:

@Component
@ConfigurationProperties("myConfigs.config1")
public class MyConfig1 {
    String field1;
    String field2;
    String field3;
}
Copy the code

As shown above, the field1, field2, field3 properties are bound to the object.

Notice that we’re using @Component. We’re actually using config classes to inject them into other classes, so we tend to register them as beans.

IgnoreInvalidFields Defaults to false. Properties of invalid properties raise exceptions by default. IgnoreUnknownFields defaults to true, and unrecognized attributes are ignored (so wrong names are ignored).

@ConfigurationProperties(prefix="config.prefix", ignoreInvalidFields=true, ignoreUnknownFields=false)
public class MyConfig {
    // fields
}
Copy the code

Spring Boot binding rules are quite loose, myField, my-field, my_field and so on can identify binding to myField.

You can set default values for fields so that they will be used if no one is passed in the configuration.

@ConfigurationProperties("your.prefix")
public class YourConfig {
    private String field = "Default"
    // setter
}
Copy the code

Class fields must have setter methods for public access.

Public setter methods are required in many cases. Alt+Insert(Alt+ N for Windows, Mac) is recommended for IDEA. Of course, you can use Lombok if you want