如何在春季引导中跳过每个配置文件的绑定属性(@ConfigurationProperties,@ConstructorB



我想为每个配置文件选择性地将字段绑定到特定类

示例代码如下...

spring:
config:
activate:
on-profile: test1
app:
cash:
conn:
connection-timeout: 1000
response-timeout: 2000
...
---
spring:
config:
activate:
on-profile: test2
@Getter
@Validated
@ConstructorBinding
@ConfigurationProperties(value = "app.cash.conn")
@RequiredArgsConstructor
public class CashBoxConnectionProperties {
@NotNull
@Positive
private final Integer connectionTimeout;
@NotNull
@Positive
private final Integer responseTimeout;
@NotNull
@PositiveOrZero
private final Integer retryMaxAttempts;
@NotNull
@Positive
private final Integer retryMaxDelay;
}

作为test1配置文件运行时,应用程序正常运行,因为设置了属性值,但在作为test2配置文件运行时,错误"绑定到目标..."因为没有app.cash.conn属性而发生。

配置文件中不需要CashBoxConnectionPropertiestest2那么除了删除@NotNull注释之外还有其他方法吗?

您可以使用@Profile("test2")注释CashBoxConnectionProperties类,这使得它仅在test2配置文件处于活动状态时才可用。为了使它工作,该类应该标记为@Component,因为@Profile只适用于春豆。

有关更多详细信息,请查看文档。

您可以使用验证组来关闭特定字段的验证。

我自己从来没有用过这个,但你可以在这里找到一个解释:https://www.baeldung.com/javax-validation-groups

最新更新