@ConfigurationProperties注解
@ConfigurationProperties为Springboot中的一个注解,用于绑定实体类与配置文件,用来把properties或者yml配置文件转化为bean来使用的。
基本使用
其基本使用方式如下:
@Component
@ConfigurationProperties(prefix = "person") //使用yaml,springboot配置,将实体类与配置绑定
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Person {
private String name;
private Integer age;
private Boolean happy;
private Date birth;
private Map<String,Object> maps;
private List<Object> list;
private Dog dog;
}
@ConfigurationProperties绑定的yaml配置文件。使用yaml配置文件相较于properties配置文件修改赋值是比较方便的。
person:
name: java
age: 3
happy: true
birth: 1996/03/11
maps: {k1: v1,k2: v2}
list:
- code
- music
- girl
dog:
name: 旺财
age: 3
源码解析
@ConfigurationProperties
/**
*外部化配置的注释。如果要绑定和验证一些外部属性(例如,来自. Properties文件),请将其添加到类定
*义或{@code @Bean}类中的{@code @Bean}方法中。绑定可以通过在带注解的类上调用setter来执行,或
*者,如果{@link ConstructorBinding @ConstructorBinding}正在使用,则通过绑定到构造函数参数来
* 执行。注意,与{@code @Value}相反,SpEL表达式不计算,因为属性值是外部化的
*
*
* @author Dave Syer
* @since 1.0.0
* @see ConfigurationPropertiesScan
* @see ConstructorBinding
* @see ConfigurationPropertiesBindingPostProcessor
* @see EnableConfigurationProperties
*/
@Target({ ElementType.TYPE, ElementType.METHOD }) //Target注解决定该注解可以加在哪些成分上,如加在类身上,或者属性身上,或者方法身上等
@Retention(RetentionPolicy.RUNTIME) //Retention注解决定MyAnnotation注解的生命周期,这个注解的生命周期一直程序运行时都存在
@Documented
public @interface ConfigurationProperties {
/*
*有效绑定到此对象的属性的前缀。是{@link #prefix()}的同义词。一个有效的前缀由一个或多个用
*点分隔的单词定义(例如{@code"acme.system.feature"})。
*@return要绑定属性的前缀
*/
@AliasFor("prefix")
String value() default "";
@AliasFor("value")
String prefix() default "";
/**
* 指示绑定到此对象时应忽略无效字段。根据所使用的绑定器,Invalid意味着无效,通常意味
* 着字段的类型错误(或者不能强制转换为正确的类型)。
* 返回标志值(默认为false)
*/
boolean ignoreInvalidFields() default false;
/**
* 指示在绑定到此对象时应忽略未知字段。未知字段可能是属性中出现错误的标志。
* 返回标志值(默认为true)
*/
boolean ignoreUnknownFields() default true;
}
下面分析该注解中@see引用的其他注解
@ConfigurationPropertiesScan
/**
* 配置扫描{@link ConfigurationProperties @ConfigurationProperties}类时使用的基本包。可以指
* 定{@link #basePackageClasses()}、{@link #basePackages()}或它的别名{@link #value()}来定*
* 义要扫描的特定包。如果没有定义特定的包,将对带有此注释的类的包进行扫描。
*
* 注意:用{@link Component @Component}注释或元注释的类不会被这个注释选中。
*
* @author Madhura Bhave
* @since 2.2.0
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(ConfigurationPropertiesScanRegistrar.class)
@EnableConfigurationProperties
public @interface ConfigurationPropertiesScan {
/**
* 属性{@link #basePackages()}的别名。允许更简洁的注释声明,例如:{@code
* @Con