项目中使用
点开一看,只是一个实体类,有set,get方法,那么这具体的值是哪来的?
注意到类有这样的注释
于是在application.yml配置文件中找到对应的配置
由此总结:
在Spring Boot中,@ConfigurationProperties
注解是用来将外部配置(通常是application.properties
或application.yml
文件中的属性)绑定到一个Java对象上。这个注解位于org.springframework.boot.context.properties
包中。
使用@ConfigurationProperties
的基本步骤如下:
-
定义一个配置属性的前缀:通过
prefix
属性指定。这个前缀用于匹配配置文件中的属性键。 -
创建一个Bean类:这个类将包含与配置文件中的属性对应的字段。
-
绑定配置属性:Spring Boot会自动将配置文件中的属性绑定到这个Bean类的字段上。
下面是一个简单的例子:
application.yml:
XXX:
property1: value1
property2: value2
Configuration Properties Bean Class:
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "XXX")
public class MyProperties {
private String property1;
private String property2;
//标准的getter和setter
public String getProperty1() {
return property1;
}
public void setProperty1(String property1) {
this.property1 = property1;
}
public String getProperty2() {
return property2;
}
public void setProperty2(String property2) {
this.property2 = property2;
}
}
在这个例子中,MyProperties
类被注解为@ConfigurationProperties
,其前缀为"XXX"。这意味着它会查找以"XXX"开头的配置属性,并将它们映射到MyProperties
类中相应的字段上。例如,"XXX.property1"将被绑定到property1
字段。
此外,@ConfigurationProperties
注解还有一些其他的特性:
- 嵌套对象:你可以定义嵌套的Bean,Spring Boot会自动处理嵌套结构的属性。
- 类型转换:Spring Boot提供了丰富的类型转换功能,可以自动将字符串配置转换为你需要的类型。
- 验证:你可以使用
javax.validation
注解来验证配置属性的值。 - 占位符替换:在配置文件中,你可以使用
${...}
占位符来引用其他配置属性。
使用@ConfigurationProperties
可以大大简化配置管理,使配置的加载和使用变得更加清晰和方便。