1. JSRs 303 and 330 in Action
Apache Bean Validation & Google Guice
GuiceCon, March 19th, 2011
Simone Tripodi
simonetripodi@apache.org
http://people.apache.org/~simonetripodi
2. Apache Bean Validation
✗ Bean Validation Specifcation (JSR303)
implementation;
✗ Efort undergoing incubation at the ASF;
✗ TCK compliant;
✗ Works on JavaSE 5 or later;
✗ Donated to the ASF from Agimatec GmbH;
✗ Released under ASL 2.0 License.
3. Apache Bean Validation
&
Google Guice
✗ Bootstrap Apache Bean Validation using Google
Guice;
✗ Obtain javax.validation.ConstraintValidator
instances using the Google Guice Injector, to easily
support the DI;
✗ Require for javax.validation.* components
injection;
✗ Intercept methods and validate method arguments.
5. obtain
javax.validation.ConstraintValidator
instances
class MyCustomValidator
Implements ConstraintValidator<MyAssert, MyType> {
private MyExternalService service;
@javax.inject.Inject
public setService(MyExternalService service) {
this.service = service;
}
public void initialize(MyAssert annotation) {
// do something
}
public boolean isValid(MyType value,
ConstraintValidatorContext context) {
return his.service.doSomething(value);
}
}
6. Require for javax.validation.*
components injection
class MyValidatorClient {
@javax.inject.Inject
private ValidatorFactory validatorFactory;
public void setValidatorFactory(ValidatorFactory
validatorFactory) {
this.validator = validator;
}
...
}
7. Require for javax.validation.*
components injection
class MyValidatorClient {
@javax.inject.Inject
private Validator validator;
public void setValidator(Validator validator) {
this.validator = validator;
}
...
}
8. Methods arguments validation
●the org.apache.bval.guice.ValidationModule comes with
an AOP interceptor automatically initialized;
●Based on @org.apache.bval.guice.Validate method
annotation
● Class<?>[] groups(): the groups have to be validated,
empty by default;
● boolean validateReturnedValue(): the returned object of
intercepted method has to be validated, false by default;
● Class<? Extends Throwable> rethrowExceptionAs(): the
exception re-thrown if a validation occurs,
javax.validation.ConstraintViolationException by
default;
● String exceptionMessage(): a custom error message
when throwing a custom exception.
9. Method arguments validation
@Validate(
groups = { Insert.class },
validateReturnedValue = true,
rethrowExceptionsAs = DummyException.class,
exceptionMessage = "Impossible adding Country{Name=%s, ISO2 Code=%s, ISO3 Code=%s}"
)
public Country insertCountry(@NotNull(groups = { Insert.class }) String name,
@NotNull(groups = { Insert.class })
@Size(max = 2, groups = { Insert.class, Update.class })
String iso2Code,
@NotNull(groups = { Insert.class })
@Size(max = 3, groups = { Insert.class, Update.class })
String iso3Code) {
Country country = new Country();
country.setName(name);
country.setIso2Code(iso2Code);
country.setIso3Code(iso3Code);
...
return country;
}