import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@ConfigurationProperties(prefix = "cust.data.employee")
@Configuration("employeeProperties")
public class Employee {
private String name;
private String dept;
//Getters and Setters go here
}
4 回答
如果您将在一个地方使用此值,则可以使用
@Value
从application.properties
加载变量,但如果您需要更集中的方式来加载此变量@ConfigurationProperties
是更好的方法 .此外,如果您需要不同的数据类型来执行验证和业务逻辑,您可以加载变量并自动转换它们 .
另一种方法是向您的bean注入Environment .
@ConfigurationProperties
可用于将.properties
(也支持.yml
)中的值映射到POJO .请考虑以下示例文件 .
.properties
Employee.java
现在可以通过自动装配
employeeProperties
来访问属性值,如下所示 .您可以使用
@Value
注释并在您正在使用的任何Spring bean中访问该属性Spring Boot文档的Externalized Configuration部分解释了您可能需要的所有细节 .