Reputation: 85
Is it possible to use the spring property validation based on another property value?
I can't use the @ConditionalOnProperty
because the property is used in a lot of places. I can't just put the @ConditionalOnProperty
for each bean.
Here is what I have:
@ConfigurationProperties
public class Property1 {
boolean property2Enabled
}
@ConfigurationProperties
public class Property2 {
@NotNull
@Size(min = 1)
String thisShouldBeValidated;
}
In this case the validation for thisShouldBeValidated
should be applied only if the value of property2Enabled
is true
.
Is it possible to do this with some spring annotation?
If I write a custom validation can I somehow get the value of the property2Enabled
if that?
Upvotes: 0
Views: 3724
Reputation: 4356
Try the Spring 4 @Conditional annotation that can be applied to @Bean methods.
import org.springframework.context.annotation.Condition;
@ConfigurationProperties
public class Property1 implements Condition{
boolean property2Enabled;
@Override
public boolean matches()
return property2Enabled;
}
}
thisShouldBeValidated should be applied only if the value of property2Enabled is true. Otherwise its ignored.
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);
}
}
As you can see, @Conditional
is given a Class that specifies the condition—in this case, Property1
.
The class given to @Conditional
can be any type that implements the Condition
interface.
Upvotes: 2