java - 来自 Bean 方法的 Immutabel ConfigurationProperties
问题描述
您可以通过ConfigurationProperties
多种方式使用 Spring 创建 -Objects。
一种方法是将@ConfigurationProperties
-Annotation添加到 -Declaration 中,@Bean
如下所示:
@Bean
@ConfigurationProperties("my.property.group")
public MyProperties myProperties() {
return new MyProperties();
}
它将从MyProperties
-class 创建一个 bean,然后使用它的setter来用配置文件中的值填充其成员。
您也可以直接在MyProperties
-Object 上添加注释,如下所示:
@ConfigurationProperties("my.property.group")
public class MyProperties {
@Getter @Setter private String myFirstValue;
@Getter @Setter private String mySecondValue;
}
通过放置@EnableConfigurationProperties(MyProperties.class)
到任何加载的配置来创建它。
也可以以不可变的方式创建此类,使用@ConstructorBinding
@ConfigurationProperties("my.property.group")
@ConstructorBinding
public class MyProperties {
@Getter private final String myFirstValue;
@Getter private final String mySecondValue;
public MyProperties(String myFirstValue, String mySecondValue) {
this.myFirstValue = myFirstValue;
this.mySecondValue = mySecondValue;
}
}
但是如何结合第一个 @Bean 方法创建不可变的 ConfigurationProperties?
我试过这样的事情:
@Bean
@ConfigurationProperties("my.property.group")
// @ConstructorBinding <---- This is not applicable to methods
public MyProperties myProperties(String myFirstValue, String mySecondValue) {
return new MyProperties(myFirstValue, mySecondValue);
}
这告诉我,它无法自动装配参数,我将考虑声明一些类型的 beanString
解决方案
推荐阅读
- apache-pulsar - 如何为 apache pulsar 设置 logrotation
- arduino-ide - Bluefruit LE with 植物区系不会恢复出厂设置
- python - 根据列的原始数据类型更改 Pandas Dataframe 中列的数据类型
- r - 无法安装 R 包“ssh”
- regex - 正则表达式在匹配前后返回指定数量的字符
- ios - 如何在集合视图的scrollviewdidScroll方法中获取indexpath
- javascript - 为什么 HTML 脚本在我的 React 应用程序中不起作用?
- c# - 如何使用 Graph API 在 Windows 窗体应用程序中显示记录的用户名?
- node.js - 使用 mocha 和 supertest 的 Typescript Express 端点覆盖率
- kubernetes - 只有在部署准备好时,Istio virtualservice 才能知道何时将流量传递给 svc?