Ric*_*d67 4 java spring immutability spring-boot
我是 Spring Boot 的新手。目前,我正在尝试创建一个 POJO 类(SystemProperties.class)来读取属性文件中的值(parameter.properties与 application.properties 分开但仍在同一目录 /src/main/resources 下。当我我在类中使用 @ConstructorBinding 以使其不可变。
- @ConstructorBinding 需要与@EnableConfigurationProperties 或@ConfigurationPropertiesScan 一起使用。
- @ConfigurationPropertiesScan 将忽略使用 @PropertySource 指定外部
*.properties 文件时需要的 @Configuration 注释。
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;
}
Run Code Online (Sandbox Code Playgroud)
B) 参数.properties
abc.test=text1
Run Code Online (Sandbox Code Playgroud)
我试图删除@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;
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,我省略了@Configuration和@PropertySource注释。
@Configuration
@PropertySource("classpath:parameter.properties")
public class PropertySourceLoader {
}
Run Code Online (Sandbox Code Playgroud)
请注意,我只是在一个新类上添加了此注释,该类仅用于加载属性文件。
最后,您可以添加@ConfigurationPropertiesScan主应用程序类以启用属性映射机制。
| 归档时间: |
|
| 查看次数: |
5122 次 |
| 最近记录: |