9.配置绑定-@ConfigurationProperties

如果我们直接使用原生配置文件的方式做配置的话,取值挺花时间的, 比如

public class getProperties {
     public static void main(String[] args) throws FileNotFoundException, IOException {
         Properties pps = new Properties();
         pps.load(new FileInputStream("a.properties"));
         Enumeration enum1 = pps.propertyNames();//得到配置文件的名字
         while(enum1.hasMoreElements()) {
             String strKey = (String) enum1.nextElement();
             String strValue = pps.getProperty(strKey);
             System.out.println(strKey + "=" + strValue);
             //封装到JavaBean。
         }
     }
 }

要遍历,还要筛选

如果用springboot提供的 @ConfigurationProperties 就会方便很多

1.先在配置文件中定义数据

比如

mycar.brand = YD
mycar.price = 5000

2.直接中实体类上使用注解 就直接绑定好了数据 ,直接拿前缀,然后在配备字段, 字段一定要和相同,不然找不到,注意要加到组件中才能使用springboot的功能

/**
 * 只有在容器中的组件,才会拥有SpringBoot提供的强大功能
 */
@Component
@ConfigurationProperties(prefix = "mycar")
public class Car {

    private String brand;
    private Integer price;

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public Integer getPrice() {
        return price;
    }

    public void setPrice(Integer price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Car{" +
                "brand='" + brand + '\'' +
                ", price=" + price +
                '}';
    }
}

 上方的方式是将Car加入到容器中了,如果没有加入到容器中就是按照下面

3.第二中方式

/**
 * 只有在容器中的组件,才会拥有SpringBoot提供的强大功能
 */
@ConfigurationProperties(prefix = "mycar")
public class Car {

 

@EnableConfigurationProperties 激活配置属性 在Car类上只是有@ConfigurationProperties 配置属性注解,但是Car并没有加入容器中,
 
为什么不直接加入到容器中 是因为可以在配置类中进行条件判断,(在自定义start中)如果想将Car加入到容器中 就在配置类中new出来,但是new出来Car是无法自动注入属性的
 
只有在配置类中加入@EnableConfigurationProperties(Car.class) 激活Car的配置属性,才能自动和mycar绑定
 
@EnableConfigurationProperties(Car.class)
//1、开启Car配置绑定功能
//2、把这个Car这个组件自动注册到容器中
public class MyConfig {
}

 

 

在某些源码中的类  没有注册组件,这个注解就可以使用了,把源码中的类使用激活配置属性注解 并加入组件,就可以直接吧yaml中的数据赋过去了
 

 

posted @ 2022-09-03 03:38  咖喱给给啊  阅读(46)  评论(0)    收藏  举报