@EnableConfigurationProperties 注解和@ConfigurationProperties注解实现配置绑定

ConfigurationProperties注解主要用来把properties配置文件转化为bean来使用的,而@EnableConfigurationProperties注解的作用是@ConfigurationProperties注解生效。如果只配置@ConfigurationProperties注解,在IOC容器中是获取不到properties配置文件转化的bean的

如果一个配置类只配置@ConfigurationProperties注解,而没有使用@Component,那么在IOC容器中是获取不到properties 配置文件转化的bean。说白了 @EnableConfigurationProperties 相当于把使用 @ConfigurationProperties 的类进行了一次注入。
测试发现 @ConfigurationProperties 与 @EnableConfigurationProperties 关系特别大。

1:写法一

1:写一个Car实体类

类上加上

@Component
@ConfigurationProperties(prefix = "mycar")

@ConfigurationProperties注解可以把application.properties文件转化为bean使用@Component注解把该bean注入到IOC容器中。

如果一个类只配置了 @ConfigurationProperties 注解,而没有使用 @Component 注解将该类加入到 IOC 容器中,那么它就不能完成 xxx.properties 配置文件和 Java Bean 的数据绑定

mycar是在如下application.properties中配置的

 

//只有在容器中的组件,才会拥有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;
    }
}

 

 

2:在application.properties配置

mycar.brand=BBA
mycar.price=100

mycar就是Car实体类上

ConfigurationProperties(prefix = "mycar")的

brand和price就是属性名

 

 

3:写一个Controller类

@RequestMapping("/web/")
@RestController
public class CarController {
    @Autowired
    private Car car;

    @PostMapping("/test")
    public Car test1(){
        return car;
    }
}

 

4:用postman进行访问,看到有返回,能读取到配置文件中的值

 

 

 

2:写法二

1:把@Component注解注视掉了,表示不往容器中注册了

 

 

2:写一个

SpringConfig配置文件

在EnableConfigurationProperties中引入car类

EnableConfigurationProperties只是声明了属性绑定

 

3:再次访问,有返回

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值