Description:
|
I have a scenario where I am validating a _List_ as _NotNull_ for a method getTest see below example:
{code} public interface IApplication { void getTest(@NotNull List<String> someList); } {code}
{code} @AutoValidator //This is similar to the MethodValidation Interceptor and using guice as DI @Slf4j public class ApplicationImpl implements IApplication { @Override public void getTest(List<String> app) { log.debug("Entered the method"); } } {code}
{code} public class ValidationInterceptor implements MethodInterceptor { @Inject private ValidatorFactory validatorFactory;
@Override public Object invoke(MethodInvocation invocation) throws Throwable { MethodValidator validator = validatorFactory.getValidator().unwrap( MethodValidator.class); //validate the all parameter values if they have been annotated with any constraints Set<MethodConstraintViolation<Object>> violations = validator.validateAllParameters(
invocation.getThis(), invocation.getMethod(),
invocation.getArguments()); if (!violations.isEmpty()) { throw new MethodConstraintViolationException(violations); }
Object result = invocation.proceed(); //validate the return values if they have been annotated with any constraints violations = validator.validateReturnValue(invocation.getThis(), invocation.getMethod(), result);
if (!violations.isEmpty()) { throw new MethodConstraintViolationException(violations); }
return result; } } {code}
Unit test: {code} public class AppTest { @Test public void getTest() { List<String> app = null; appSvc.getTest(app); } } {code}
|