[英]Where the validation should be done in a 3 layers Entity-Repository-Service application?
I am struggling to define where the validation process would be better placed in the different layers of the application? 我正在努力定义验证过程在应用程序的不同层中的位置? (I am not talking about user input validation here, I'm really talking about the object consistency).
(我这里不是在谈论用户输入验证,我真的在谈论对象的一致性)。
A simple case: 一个简单的案例:
Blog
entity which has a field List<Comment>
, and a method List<Comment>
Blog
实体和方法 boolean addComment(Comment comment)
comment
parameter of the boolean addComment(Comment comment)
is null
, which would return false
boolean addComment(Comment comment)
的comment
参数是否为null
,这将返回false
To me, such a check could be done in both the Service
and Entity
layers to ensure that everything is consistent at any layer. 对我来说,可以在
Service
和Entity
层中完成这样的检查,以确保任何层的所有内容都是一致的。
But it seems redundant and something tells me that only one layer should have that responsability. 但这似乎是多余的,有些东西告诉我,只有一层应该具有这种责任感。
I would say the highest one in the stack, thus the Service
layer should do this validation? 我会说堆栈中最高的一个,因此
Service
层应该进行此验证吗? But when I'm writing my unit tests, it feels wrong to not make that check again in the Entity
layer. 但是当我编写单元测试时,在
Entity
层中再次进行检查是不对的。
My recommendation is to put these at the "public" interfaces to the services. 我的建议是将这些接口放在服务的“公共”接口上。 With any public method you can't give any kind of guarantees as to the quality of input.
使用任何公共方法,您都无法对输入质量提供任何保证。
Here is the reasoning: 这是推理:
The easiest way to enforce this logic is to create an aspect and put the validation code in there. 实施此逻辑的最简单方法是创建方面并将验证代码放在那里。
<aop:aspect ref="validator" order="3">
<aop:before method="doValidation" pointcut="execution(public * com.mycompany.myapp.services.*.*(..))"/>"/>
</aop:aspect>
So, this aspect bean example covers all public methods in the service layer. 因此,此方面bean示例涵盖服务层中的所有公共方法。
@Aspect
public class ServiceValidator{
private Validator validator;
public ServiceValidator() {
}
public ServiceValidator(Validator validator) {
this.validator = validator;
}
public void doValidation(JoinPoint jp){
for( Object arg : jp.getArgs() ){
if (arg != null) {
// uses hibernate validator
Set<ConstraintViolation<Object>> violations = validator.validate(arg);
if( violations.size() > 0 ){
// do something
}
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.