[英]How to use @ConfigurationProperties annotation in Spring Boot
[英]How to use @ConstructorBinding and @PropertySource together with @ConfigurationProperties with in Spring Boot 2.2.4?
我是 Spring Boot 的新手。 目前,我正在尝试创建一个 POJO 类( SystemProperties.class )来读取属性文件中的值( parameter.properties与 application.properties 分开但仍在同一目录 /src/main/resources 下。当我我在类中使用 @ConstructorBinding 以使其不可变。
- @ConstructorBinding 需要与@EnableConfigurationProperties 或@ConfigurationPropertiesScan 一起使用。
- @ConfigurationPropertiesScan 将忽略使用 @PropertySource 指定外部时需要的 @Configuration 注释
*.properties 文件。
A) SystemProperties.class
@Configuration
@PropertySource("classpath:parameter.properties")
@ConstructorBinding
@ConfigurationProperties(prefix = "abc")
public class SystemProperties {
private final String test;
public SystemProperties (
String test) {
this.test = test;
}
public String getTest() {
return test;
}
B) 参数.properties
abc.test=text1
我试图删除@PropertySource 注释,但无法检索该值,除非它来自 application.properties。 任何帮助是极大的赞赏!
解决这个问题的方法是将类分成具有两个不同关注点的两个类。 使用这种解决方案,您可以保留您创建的 SystemProperties 类,并另外添加另一个类,仅用于加载属性文件参数,使它们可用于您的应用程序。
解决方法如下:
@ConstructorBinding
@ConfigurationProperties(prefix = "abc")
public class SystemProperties {
private final String test;
public SystemProperties(
String test) {
this.test = test;
}
public String getTest() {
return test;
}
}
请注意,我省略了@Configuration
和@PropertySource
注释。
@Configuration
@PropertySource("classpath:parameter.properties")
public class PropertySourceLoader {
}
请注意,我只是在一个新类上添加了此注释,该类仅用于加载属性文件。
最后,您可以在主应用程序类上添加@ConfigurationPropertiesScan
以启用属性映射机制。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.