Spring boot 下的 配置绑定机制

60 阅读1分钟

场景 :

你需要把配置文件 绑定到某个类的属性上

方式一

//@Component

//前提时 这个类 必须交给 spring 管理

@ConfigurationProperties(prefix = “mycar”) //根据配置文件的前缀 把配置文件 配置参数 赋值到 对象属性上

这俩注解配合使用

package com.springboot.web.entity;

import org.springframework.boot.context.properties.ConfigurationProperties;

/**
 * @User: Json
 * @Date: 2022/6/9
 * 只有在容器的组件才能使用 springboot 提供的功能
 **/
//1. 方式一
//@Component
//前提时 这个类 必须交给 spring 管理
@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;
    }

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

    public Integer getPrice() {
        return price;
    }

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

方式二:

@EnableConfigurationProperties(Car.class) // 应用场景 比如 你用的时第三方的包 需要把配置信息注入到第三方里 就可以使用这种 在配置文件上打这个

@ConfigurationProperties(prefix = “mycar”) //根据配置文件的前缀 把配置文件 配置参数 赋值到 对象属性上 在需要配置的类上打这个

这俩注解配合使用

1.png

2.png