springboot注解之@EnableConfigurationProperties注解

目录

一 . @EnableConfigurationProperties注解的作用

二   举例说明

三、结论 


一 . @EnableConfigurationProperties注解的作用

通常是用来将propertiesyml配置文件属性转化为bean对象使用

@EnableConfigurationProperties 注解的作用是:

让使用了 @ConfigurationProperties 注解的类生效,并且将该类注入到 IOC 容器中,交由 IOC 容器进行管理

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

二   举例说明

第一种情况:如果不添加@EnableConfigurationProperties注解  那么在使用@ConfigurationProperties 注解的时候就必须一定要添加 @Component 注解

1、application.properties

xiaomao.name=xiaomaomao

xiaomao.age=27

2、MyConfigurationProperties 这个实体类中必须要加上 @Component ,使这个类注入到 IOC 容器中,否则就无法从容器中获取到这个类的对象实例

@Component

@ConfigurationProperties(prefix = "xiaomao")  //读取配置文件application.properties 或 application.yml 文件的参数

public class MyConfigurationProperties {

    // 省略 get、set、toString 方法

    private String name;

    private Integer age;

    private String gender;

}

3、HelloController

@RestController

public class HelloController {

    @Autowired

    private MyConfigurationProperties config;

    @GetMapping("/config")

    private String testConfigurationProperties(){

        System.out.println(config);

        return "SUCCESS!!!";

    }

}

4、测试结果


MyConfigurationProperties{name='xiaomaomao', age=27, gender='null'}

第二种情况 :如果添加了@EnableConfigurationProperties注解  在使用@ConfigurationProperties 注解的时候    实体类就不需要加上 @Component 注解了

三、结论 

如果要使 xxx.properties 配置文件与 Java Bean 动态绑定,那么就必须将这个 Java Bean 加入到容器中,并且需要在该类上使用 @ConfigurationProperties 注解

@EnableConfigurationProperties(A.class)的作用就是如果 A 这个类上使用了 @ConfigurationProperties 注解,那么 A 这个类会与 xxx.properties 进行动态绑定,并且会将 A 这个类加入 IOC 容器中,并交由 IOC 容器进行管理

如果@ConfigurationProperties是在第三方包中,那么@component是不能注入到容器的。只有@EnableConfigurationProperties才可以注入到容器

参考:  https://blog.csdn.net/Cloud_July/article/details/122720164

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值