|
1
|
|
|
package io.github.ro4.spelvalidation; |
|
2
|
|
|
|
|
3
|
|
|
import org.springframework.beans.BeansException; |
|
4
|
|
|
import org.springframework.beans.factory.BeanFactory; |
|
5
|
|
|
import org.springframework.beans.factory.BeanFactoryAware; |
|
6
|
|
|
import org.springframework.context.expression.BeanFactoryResolver; |
|
7
|
|
|
import org.springframework.expression.spel.standard.SpelExpressionParser; |
|
8
|
|
|
import org.springframework.expression.spel.support.StandardEvaluationContext; |
|
9
|
|
|
import org.springframework.util.ObjectUtils; |
|
10
|
|
|
import org.springframework.util.StringUtils; |
|
11
|
|
|
|
|
12
|
|
|
import javax.validation.ConstraintValidator; |
|
13
|
|
|
import javax.validation.ConstraintValidatorContext; |
|
14
|
|
|
|
|
15
|
1 |
|
public class SpELValidator implements ConstraintValidator<SpELAssert, Object>, BeanFactoryAware { |
|
16
|
|
|
|
|
17
|
1 |
|
private static final SpelExpressionParser PARSER = new SpelExpressionParser(); |
|
18
|
|
|
|
|
19
|
|
|
private String expression; |
|
20
|
|
|
|
|
21
|
|
|
private StandardEvaluationContext spELCtx; |
|
22
|
|
|
|
|
23
|
|
|
private BeanFactory beanFactory; |
|
24
|
|
|
|
|
25
|
|
|
private String alias; |
|
26
|
|
|
|
|
27
|
|
|
private String message; |
|
28
|
|
|
|
|
29
|
|
|
private String reportOn; |
|
30
|
|
|
|
|
31
|
|
|
@Override |
|
32
|
|
|
public void initialize(SpELAssert anno) { |
|
33
|
1 |
|
if (!ObjectUtils.isEmpty(anno.expression())) { |
|
34
|
1 |
|
expression = StringUtils.arrayToDelimitedString(anno.expression(), " "); |
|
35
|
1 |
|
} else if (!ObjectUtils.isEmpty(anno.value())) { |
|
36
|
1 |
|
expression = anno.value(); |
|
37
|
|
|
} |
|
38
|
1 |
|
this.spELCtx = new StandardEvaluationContext(); |
|
39
|
1 |
|
spELCtx.setBeanResolver(new BeanFactoryResolver(beanFactory)); |
|
40
|
1 |
|
this.alias = anno.alias(); |
|
41
|
1 |
|
this.message = anno.message(); |
|
42
|
1 |
|
this.reportOn = anno.reportOn(); |
|
43
|
1 |
|
} |
|
44
|
|
|
|
|
45
|
|
|
@Override |
|
46
|
|
|
public boolean isValid(Object value, ConstraintValidatorContext context) { |
|
47
|
1 |
|
spELCtx.setVariable(alias, value); |
|
48
|
1 |
|
boolean result = Boolean.TRUE.equals(PARSER.parseExpression(expression).getValue(spELCtx, Boolean.TYPE)); |
|
49
|
1 |
|
if (!result && !reportOn.isEmpty()) { |
|
50
|
|
|
context.disableDefaultConstraintViolation(); |
|
51
|
|
|
context.buildConstraintViolationWithTemplate(message).addPropertyNode(reportOn).addConstraintViolation(); |
|
52
|
|
|
} |
|
53
|
1 |
|
return result; |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
@Override |
|
57
|
|
|
public void setBeanFactory(BeanFactory beanFactory) throws BeansException { |
|
58
|
1 |
|
this.beanFactory = beanFactory; |
|
59
|
1 |
|
} |
|
60
|
|
|
} |
|
61
|
|
|
|