@EnableConfigurationProperties的使用方式以及作用

@EnableConfigurationProperties的使用方式以及作用_enaboleaotuconfigproperties-CSDN博客

文章目录

1. 结论

  1. 在@ConfigurationProperties的使用,把配置类的属性与yml配置文件绑定起来的时候,还需要加上@Component注解才能绑定并注入IOC容器中,若不加上@Component,则会无效。
  2. @EnableConfigurationProperties的作用:则是将让使用了 @ConfigurationProperties 注解的配置类生效,将该类注入到 IOC 容器中,交由 IOC 容器进行管理,此时则不用再配置类上加上@Component。

2. 代码例子

1. @ConfigurationProperties的使用

(提外话:具体的yml文件字符串、List、Map的书写方式并使用@ConfigurationProperties注入配置类.) 点这里
配置类

@Component
@ConfigurationProperties(prefix = "demo")
@Data
public class DemoConfig {
    private String userName;
    private String age;
}
  • 1

yml配置文件

demo:
  user-name: hello
  age: 18

测试代码

@Component
public class demo implements ApplicationRunner {

    @Autowired
    DemoConfig demoConfig;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println(demoConfig);
    }
}

结果图:
在这里插入图片描述

2. @EnableConfigurationProperties的使用

当去掉配置类的@Component时候,则会报下面错误提示:
在这里插入图片描述
在测试代码上加上@EnableConfigurationProperties,参数指定那个配置类,该配置类上必须得有@ConfigurationProperties注解

@Component
@EnableConfigurationProperties(DemoConfig.class)
public class demo implements ApplicationRunner {

    @Autowired
    DemoConfig demoConfig;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println(demoConfig);
    }
}

结果图,仍然可以绑定
在这里插入图片描述

3. 为什么会有@EnableConfigurationProperties出现呢?

  1. 有的人可能会问,直接在配置类上加@Component注解,不就可以了吗,为什么还要有@EnableConfigurationProperties出现呢?
  2. 敬请期待,待我写到EnableAutoConfiguration自动装配的时候,会豁然开朗滴。
  3. 文章已经写好:
    springboot中EnableAutoConfiguration自动装配的使用(厉害)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值