ConfigurationProperties和EnableConfigurationProperties的使用
...大约 1 分钟
结论
当使用@ConfigurationProperties
来将配置类的属性与yaml配置文件绑定时,必须添加@Component
注解才能使绑定生效并注入到IOC容器中,否则会失效。
而@EnableConfigurationProperties
的作用则是让使用了@ConfigurationProperties
注解的配置类生效,将其注入到IOC容器中,不需要额外添加@Component
注解。
代码例子
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
@RequiredArgsConstructor
public class demo implements ApplicationRunner {
private final DemoConfig demoConfig;
@Override
@SneakyThrows
public void run(ApplicationArguments args){
System.out.println(demoConfig);
}
}
ApplicationRunne接口
ApplicationRunner
接口是Spring Boot中的一个接口,用于在Spring Boot应用启动后执行一些特定的逻辑。该接口定义了一个方法run
,在Spring Boot应用启动完成后,Spring容器会调用run
方法,并传入应用的参数。
结果

2. @EnableConfigurationProperties的使用
当去掉配置类的@Component时候,则会报下面错误提示:

新建一个配置类,加上@EnableConfigurationProperties,参数指定配置类(DemoConfig),该配置类(DemoConfig )上必须得有@ConfigurationProperties注解

3. 为什么会有@EnableConfigurationProperties出现呢?
有的人可能会问,直接在配置类上加@Component注解,不就可以了吗,为什么还要有@EnableConfigurationProperties出现呢?