gpt4 book ai didi

java - Spring 条件属性验证

转载 作者:行者123 更新时间:2023-12-02 02:50:59 26 4
gpt4 key购买 nike

是否可以使用基于另一个属性值的 spring 属性验证?

我无法使用@ConditionalOnProperty,因为该属性已在很多地方使用。我不能只为每个 bean 添加 @ConditionalOnProperty

这是我所拥有的:

@ConfigurationProperties
public class Property1 {
boolean property2Enabled
}

@ConfigurationProperties
public class Property2 {
@NotNull
@Size(min = 1)
String thisShouldBeValidated;

}

在这种情况下,仅当 property2Enabled 的值为 true 时,才应应用 thisShouldBeValidated 验证。

是否可以通过一些 spring 注释来做到这一点?如果我编写自定义验证,我可以以某种方式获取 property2Enabled 的值吗?

最佳答案

尝试可应用于 @Bean 方法的 Spring 4 @Conditional 注释。

import org.springframework.context.annotation.Condition;

@ConfigurationProperties
public class Property1 implements Condition{
boolean property2Enabled;

@Override
public boolean matches()
return property2Enabled;
}
}

仅当 property2Enabled 的值为 true 时,才应应用 thisShouldBeValidated。否则将被忽略。

import org.springframework.context.annotation.Condition;

public class Property2 {
@NotNull
@Size(min = 1)
String thisShouldBeValidated;

@Bean
@Conditional(Property1.class)
void Property2 yourMethod() {
system.out.println("whatever"+ thisShouldBeValidated);
}
}

如您所见,@Conditional 被赋予一个指定条件的类,在本例中为 Property1。赋予@Conditional的类可以是实现Condition的任何类型界面

关于java - Spring 条件属性验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43852442/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com