作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我可以使用 Hibernate Validator (w/i Spring boot)创建自定义约束,其中验证取决于子类吗?示例:
public class Engine {
@NotEmpty
private String name;
@NotNull
private int power;
@NotNull // HERE I ONLY NEED VALIDATE IF THIS CLASS ARE ONE PROP FROM Car Class
private int color;
... getter and setter
}
Here I have 2 classes,
public class Car {
@NotEmpty
private String name;
@Valid
private Engine engine;
... getter and setter
}
public class Bike {
@NotEmpty
private String name;
@Valid
private Engine engine; // HERE I DONT NEED TO VALIDATE THE COLOR
... getter and setter
}
最佳答案
您应该能够使用 @ConvertGroup
执行您想要的操作:
组接口(interface):
public interface BasicEngineChecks {
}
public interface ExtendedEngineChecks {
}
更新的示例:
@GroupSequence({ BasicEngineChecks.class, ExtendedEngineChecks.class })
public class Engine {
@NotEmpty(groups = BasicEngineChecks.class)
private String name;
@NotNull(groups = BasicEngineChecks.class)
private int power;
@NotNull(groups = ExtendedEngineChecks.class)
private int color;
// ...
}
汽车没有什么特别的。级联验证将通过默认组,该组将转换为 BasicEngineChecks
以及 ExtendedEngineChecks
public class Car {
@NotEmpty
private String name;
@Valid
private Engine engine;
// ...
}
对于Bike
,我们只进行显式转换,评估BasicEngineChecks
:
public class Bike {
@NotEmpty
private String name;
@Valid
@ConvertGroup(from = Default.class, to = BasicEngineChecks.class)
private Engine engine;
// ...
}
关于java - Hibernate validator 自定义约束取决于基类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36366668/
我是一名优秀的程序员,十分优秀!