@ConfigurationProperties

@ConfigurationProperties注解用于自动配置绑定,可以将application.properties,application.yml 配置中的值注入到bean对象上。
该注解使用必须将对象注入到IOC容器中才有配置绑定的功能。

  1. @Target({ElementType.TYPE, ElementType.METHOD})
  2. @Retention(RetentionPolicy.RUNTIME)
  3. @Documented
  4. @Indexed
  5. public @interface ConfigurationProperties {
  6. @AliasFor("prefix")
  7. String value() default "";
  8. @AliasFor("value")
  9. String prefix() default "";
  10. //true会自动忽略值类型不匹配的字段,false如果值类型不匹配将会爆出异常
  11. boolean ignoreInvalidFields() default false;
  12. //true会忽略掉对象中未知的字段,false当出现未知字段时会出现异常
  13. boolean ignoreUnknownFields() default true;
  14. }

使用

在application.yml配置文件里面写上自定义的属性

  1. student:
  2. name: xiaoming
  3. age: 10
  4. likes: [篮球,足球]
  5. scoreMap: {语文:90, 数学:95}

在类上使用@ConfigurationProperties(prefix =”student”)注解。
其中的参数prefix设置一个前缀。在配置文件中就去找这个前缀,找到后把属性,注入到这个对象里面,感觉名字注入

  1. @Component
  2. @ConfigurationProperties(prefix ="student")
  3. public class Student {
  4. private String name;
  5. private int age;
  6. private List<String> likes;
  7. private Map<String, Integer> scoreMap;
  8. //以上全部属性都需要set方法才能注入
  9. }

还可以标记到方法上

  1. @Configuration
  2. public class MyConfig {
  3. @Bean
  4. @ConfigurationProperties(prefix = "student")
  5. public Student student(){
  6. return new Student();
  7. }
  8. }