(Spring Bean详细讲解 什么是Bean?_鹿‘s的博客-优快云博客_springbean
Spring源码中大量使用了ConfigurationProperties注解,通过与其他注解配合使用,能够实现Bean的按需配置。
该注解有一个prefix属性,通过指定的前缀,绑定配置文件中的配置,该注解可以放在类上,也可以放在方法上。
例如:配置文件中
Car类中:
@Component
//将配置文件application.properties中的属性进行绑定,
// 第一种方式:此类放到容器中加上@Component注解
//第二种方式:在Myconfig中使用注解@EnableConfigurationProperties(Car.class)
// @EnableConfigurationProperties(Car.class)功能:
// 1. 开启Car配置绑定功能
// 2. 把这个Car这个组件自动注册到容器中,就不用写@Component
@ConfigurationProperties(prefix = "mycat")
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Car {
private String name;
public Integer price;
}
@ConfigurationProperties(prefix = "mycat")与配置文件中属性进行绑定
2.两种组合注解
1. @EnableConfigurationProperties(Car.class) +@ConfigurationProperties(prefix = "mycat"配置MyConfig类上标注开启Car类绑定功能,把这个Car类自动注册到容器中
2. @Component+@ConfigurationProperties(prefix = "mycat)
这样就能将实体类放入容器中,并与配置文件进行绑定
相当于setName以及setPrice