@EnableConfigurationProperties的使用方式以及作用

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;
}

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. 文章已经写好:
经验分享 程序员 微信小程序 职场和发展