需求:校验入口方法上的参数。
思路:AOP 的方法拦截器搜索入口方法上 Validator(接口) 类型的参数。拿到这些 Validator 接口的实现后进行校验。
接口定义:
public interface Validator {
/**
* 校验多个参数
* @param values 多个待被校验的值
* @throws ValidateException
*/
void validate(Object... values) throws ValidateException;
}
public class ValidateException extends Exception {
public ValidateException(String msg) {
super(msg);
}
}
public class ValidateException extends Exception {
public ValidateException(String msg) {
super(msg);
}
}
拦截器的实现:
@IocBean
final public class ValidationInterceptor implements MethodInterceptor {
public void filter(InterceptorChain chain) throws Throwable {
Object[] args = chain.getArgs();
//没有 Validator 接口的实现者
List<Object> validators = Stream.of(args)
.filter(arg -> Validator.class.isAssignableFrom(arg.getClass()))
.collect(Collectors.toList());
if (validators.isEmpty()) {
chain.doChain();
return;
}
List<Object> toBeValids = Stream.of(args)
.filter(arg -> !Validator.class.isAssignableFrom(arg.getClass()))
.collect(Collectors.toList());
if (!toBeValids.isEmpty()) {
for (Object va : validators) {
if (va instanceof Validator)
((Validator) va).validate(toBeValids.toArray());
}
}
chain.doChain();
}
}
控制器上使用AOP拦截器进行校验:
@At(value = "/clockonoff", methods = {"POST", "PUT"})
@Filters( @By(type= AuthorzationAdminFilter.class, args = {"ioc:authorzationAdminFilter"}) )
@AdaptBy(type=JsonAdaptor.class)
@Aop("validationInterceptor")
public int updateClockOnOffConfig(
@Param("on") Time onTime,
@Param("off") Time offTime,
@Inject("clockOnOffValidator") ClockOnOffValidator validator) {
return sysService.updateClockOnOffConfig(onTime, offTime);
}
其中, ClockOnOffValidator 类型是实现了Validator