Spring Boot @ConfigurationProperties 配置绑定

来自姬鸿昌的知识库
跳到导航 跳到搜索

https://www.bilibili.com/video/BV19K4y1L7MT/?p=12

旧的 properties 文件参数读取封装到 Java Bean

public class getProperties {

    public static void main(String[] args) throws IOException {

        Properties pps = new Properties();
        pps.load(new FileInputStream("a.properties"));
        Enumeration<?> enumeration = pps.propertyNames(); //得到配置文件的名字
        while (enumeration.hasMoreElements()) {
            String strKey = (String) enumeration.nextElement();
            String strValue = pps.getProperty(strKey);
            System.out.println(strKey + "=" + strValue);
            /**
             * 封装到 Java Bean
             * ……
             */

        }

    }

}

使用 @ConfigurationProperties 和 @Component 实现配置绑定和 bean 注册

/**
 * 只有在容器中的组件,才会拥有 Spring Boot 提供的强大功能
 */
@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 +
                '}';
    }
}

application.yaml

mycar:
  brand: BYD
  price: 100000
@RestController
public class HelloController {

    @Autowired
    Car car;

    @RequestMapping("/car")
    public Car car() {
        return car;
    }

}

http 请求 http://localhost:8888/car,得到

{
"brand": "BYD",
"price": 100000
}

使用 @EnableConfigurationProperties 和 @ConfigurationProperties 实现配置绑定和 bean 注册

@Import({User.class, DBHelper.class})
@Configuration(proxyBeanMethods = false) //告诉 SpringBoot 这是一个配置类 == 配置文件
@ConditionalOnMissingBean(name = "tom")
@ImportResource("classpath:beans.xml")
@EnableConfigurationProperties(Car.class)
//1、开启 Car 的配置绑定功能
//2、把这个 Car 组件自动注册到容器中
public class MyConfig {
……
//@Component
@ConfigurationProperties(prefix = "mycar")
public class Car {
……