Spring Annotations @ConfigurationProperties

@ConfigurationProperties is an external configuration of annotation, such as external .propertiesproperties file. Using this annotation can be achieved outside of the property is bound to Bean instance, it can also be achieved verify the legitimacy of external properties in the process of binding.

A, @ ConfigurationProperties how to use

@ConfigurationProperties notes are usually placed on the use of the class, such as:

@ConfigurationProperties(prefix = "student",ignoreInvalidFields = false,ignoreUnknownFields = false)
public class StudentProperties {}

The method may also be placed on the inside @Configuration @Bean class annotated notes, such as:

@Configuration
public class TeacherConfig {
    @Bean
    @ConfigurationProperties(prefix = "teacher")
    public Teacher teacher(){//Spring会把@ConfigurationProperties注解的外部配置绑定到new Teacher()生成的实例对应属性上
        return new Teacher();
    }
}

Note : @ConfigurationProperties not comment to instantiate Bean, Bean instantiated nor will join IOC container just after Bean instance attribute bindings, and verify the legitimacy of the property value. Also
it means that @ConfigurationProperties annotations can not be used alone, and other usually can instantiate Bean and Bean joined the IOC containers with annotations take effect, usually have the following three options:

(1). @ConfigurationProperties+@Configuration/@Component

@Configuration
@ConfigurationProperties(prefix = "")
public class StudentProperties {}

(2). @ConfigurationProperties+@EnableConfigurationProperties(Xxx.class)

@ConfigurationProperties(prefix = "")
public class StudentProperties {}

@EnableConfigurationProperties(StudentProperties.class)
@SpringBootApplication
public class ConfigurationPropertiesApplication implements ApplicationRunner {

    @Autowired
    private StudentProperties studentProperties;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println(studentProperties.toString());
    }
}

@EnableConfigurationProperties source Interpretation:
. Support for the Enable @link Configuration Properties @ConfigurationProperties {} {@code @ConfigurationProperties} annotated Beans Beans CAN BE Registered Way in The Standard (Example for the using @link {Methods} @Bean Bean) or, for Convenience, can be specified directly on this annotation.
open support for @ConfigurationProperties notes of Bean, Bean annotated the @ConfigurationProperties registered into the IOC container. In other words, Spring scans opened @ConfigurationProperties annotated class is instantiated, and the binding property to the value of the specified prefix @ConfigurationProperties class instance.

(3).@ConfigurationProperties+@ConfigurationPropertiesScan

@ConfigurationProperties(prefix = "student",ignoreInvalidFields = false,ignoreUnknownFields = false)
public class StudentProperties {}

@ConfigurationPropertiesScan
@SpringBootApplication
public class ConfigurationPropertiesApplication implements ApplicationRunner {

    @Autowired
    private StudentProperties studentProperties;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println(studentProperties.toString());
    }
}

@ConfigurationPropertiesScan
see source, Spring scans @ConfigurationPropertiesScan annotations configured packages / class @ConfigurationProperties annotation instantiate a class, then the specified prefix @ConfigurationProperties property values bound to the instance of the class, and add IOC container.

Two, @ ConfigurationProperties annotation class attribute value binding way

(1) Setter method @ConfigurationProperties class annotated
@ConfigurationProperties annotation attributes required in this manner must have a class method Setter

(2) class constructor @ConfigurationProperties annotation
to bind property values by the constructor must @ConstructorBindingannotation specified attribute value binding mode is bound to the constructor class or the constructor. such as:

@ConfigurationProperties(prefix = "student",ignoreInvalidFields = false,ignoreUnknownFields = false)
public class StudentProperties {

    @ConstructorBinding
    public StudentProperties(String name, int age, Grade grade, School school, List<String> hobbyList, Duration allowLateTime) {
        this.name = name;
        this.age = age;
        this.grade = grade;
        this.school = school;
        this.hobbyList = hobbyList;
        this.allowLateTime = allowLateTime;
    }
}

Third, property values can not be bound, rewriting Converter 或 ConditionalConverterinterfaces to solve

If the .propertiesproperty value can not bind to the file @ConfigurationPropertieswhen the class attribute annotations, you can customize the converter to solve for this property. Custom converter must implement the Converter 或ConditionalConverterinterface.
Custom converter must also @ConfigurationPropertiesBindingcomment that he is a named configuration properties binder and join IOC container. During bind property values, Spring will find specific binding from the binding to convert IOC container. such as:

#properties配置文件
student:
  grade: 三年级
@ConfigurationProperties(prefix = "student",ignoreInvalidFields = false,ignoreUnknownFields = false)
public class StudentProperties {

    /**
     * 年级
     */
    private Grade grade;
}

/**
 * @desc: Grade转换器
 */
@Component
@ConfigurationPropertiesBinding
public class GradeConverter implements Converter<String,Grade> {

    @Override
    public Grade convert(String source) {
        Grade grade = new Grade();
        grade.setName(source);
        return grade;
    }
}

/**
 * @desc: 年级
 */
@ToString
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Grade {

    private String name;
    private String school;
    
}

Fourth, the attribute value verification

(1) @ConfigurationProperties annotation itself with unknown properties and properties illegal authentication

@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ConfigurationProperties {

	/**
	 * Flag to indicate that when binding to this object invalid fields should be ignored.
	 * Invalid means invalid according to the binder that is used, and usually this means
	 * fields of the wrong type (or that cannot be coerced into the correct type).
	 * @return the flag value (default false)
	 */
	boolean ignoreInvalidFields() default false;

	/**
	 * Flag to indicate that when binding to this object unknown fields should be ignored.
	 * An unknown field could be a sign of a mistake in the Properties.
	 * @return the flag value (default true)
	 */
	boolean ignoreUnknownFields() default true;
}

(2) using the authentication framework hibernate validator to verify or javax.validation

@Validated
@Configuration
@ConfigurationProperties(prefix = "student",ignoreInvalidFields = false,ignoreUnknownFields = false)
public class StudentProperties {

    @NotEmpty(message = "学生姓名不能为空")
    private String name;
}

Fifth, use Spring Boot Configuration Processor complete auto-complete

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

After re-build the project, configuration processor creates a target / classes / META-INF / spring-configuration-metadata.json file.

{
  "groups": [
    {
      "name": "student",
      "type": "com.mapc.annotation.StudentProperties",
      "sourceType": "com.mapc.annotation.StudentProperties"
    }
  ],
  "properties": [
    {
      "name": "student.age",
      "type": "java.lang.Integer",
      "description": "年龄",
      "sourceType": "com.mapc.annotation.StudentProperties",
      "defaultValue": 0
    },
    {
      "name": "student.name",
      "type": "java.lang.String",
      "description": "姓名",
      "sourceType": "com.mapc.annotation.StudentProperties"
    }]
}

Demo Source:

References:

Published 35 original articles · won praise 32 · views 90000 +

Guess you like

Origin blog.csdn.net/u012995888/article/details/103863152