@ConfigurationProperties
@ConfigurationProperties注解用于自动配置绑定,可以将application.properties,application.yml 配置中的值注入到bean对象上。
该注解使用必须将对象注入到IOC容器中才有配置绑定的功能。
@Target({ElementType.TYPE, ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)@Documented@Indexedpublic @interface ConfigurationProperties {@AliasFor("prefix")String value() default "";@AliasFor("value")String prefix() default "";//true会自动忽略值类型不匹配的字段,false如果值类型不匹配将会爆出异常boolean ignoreInvalidFields() default false;//true会忽略掉对象中未知的字段,false当出现未知字段时会出现异常boolean ignoreUnknownFields() default true;}
使用
在application.yml配置文件里面写上自定义的属性
student:name: xiaomingage: 10likes: [篮球,足球]scoreMap: {语文:90, 数学:95}
在类上使用@ConfigurationProperties(prefix =”student”)注解。
其中的参数prefix设置一个前缀。在配置文件中就去找这个前缀,找到后把属性,注入到这个对象里面,感觉名字注入
@Component@ConfigurationProperties(prefix ="student")public class Student {private String name;private int age;private List<String> likes;private Map<String, Integer> scoreMap;//以上全部属性都需要set方法才能注入}
还可以标记到方法上
@Configurationpublic class MyConfig {@Bean@ConfigurationProperties(prefix = "student")public Student student(){return new Student();}}
