Bean Validation 1.1 What's cooking? 05.04.2013 Gunnar Morling - - PowerPoint PPT Presentation
Bean Validation 1.1 What's cooking? 05.04.2013 Gunnar Morling - - PowerPoint PPT Presentation
Bean Validation 1.1 What's cooking? 05.04.2013 Gunnar Morling JBoss, by Red Hat Bean Validation 1.1 JSR 349 Final Approval Ballot nchste Woche! Vollstndig offen Issue-Tracker Mailingliste GitHub:
05.04.2013 Bean Validation 1.1 – What's cooking? /13
Bean Validation 1.1
- JSR 349 – Final Approval Ballot nächste Woche!
- Vollständig offen
– Issue-Tracker – Mailingliste – GitHub:
- Spezifikation
- Referenzimplemen-
tierung
- TCK
- Website
2
05.04.2013 Bean Validation 1.1 – What's cooking? /13
Dependency Injection
- Dependency Injection via CDI
– ConstraintValidator-Implementierungen – – – – – – – –
–
– MessageInterpolator, TraversableResolver, ConstraintValidatorFactory etc.
public public class class PastValidator PastValidator implements implements ConstraintValidator< ConstraintValidator<Past Past, Date> { , Date> { @Inject @Inject private private TimeService TimeService timeService timeService; public public void void initialize( initialize(Past Past constraintAnnotation) { constraintAnnotation) { } public public boolean boolean isValid(Date date, ConstraintValidatorContext context) { isValid(Date date, ConstraintValidatorContext context) { if if ( date == ( date == null null ) { ) { return return true true; } return return date.before( date.before( timeService timeService.getCurrentTime() ); .getCurrentTime() ); } }
3
05.04.2013 Bean Validation 1.1 – What's cooking? /13
Methodenvalidierung (I)
- Validierung von Methodenparametern und -rückgabewerten
beim Aufruf
- Erfordert Interceptor, AOP, Proxy etc.
4
05.04.2013 Bean Validation 1.1 – What's cooking? /13
Methodenvalidierung (II)
- Parameterprüfung – “old school”
- Nachteile
– Manuelle Prüfung – Redundanz – Schnell uneinheitlich
/** /** * Places an order. * Places an order. * * * @param @param customerCode Must not be null and between 3 and 20 characters. customerCode Must not be null and between 3 and 20 characters. * * @param @param item Must not be null. item Must not be null. * * @param @param quantity Must be larger or equal than 1. quantity Must be larger or equal than 1. */ */ public public void void placeOrder(String customerCode, Item item, placeOrder(String customerCode, Item item, int int quantity) { quantity) { validateCustomerCode(customerCode); validateCustomerCode(customerCode); if if(item == (item == null null) ) throw throw new new IllegalArgumentException(); IllegalArgumentException(); if if(quantity < 1) (quantity < 1) throw throw new new IllegalArgumentException(); IllegalArgumentException(); //Actual business logic... //Actual business logic... }
5
05.04.2013 Bean Validation 1.1 – What's cooking? /13
Methodenvalidierung (III)
- Parameterprüfung – “Bean Validation way”
- Vorteile
– Validierung einheitlich als Aspekt implementiert – Constraints Teil der JavaDoc – “Programming by Contract”
- Aktiv per Default für CDI Beans und JAX-RS Resourcen
public public void void placeOrder( placeOrder( @NotNull @NotNull @Size @Size(min=3, max=20) String customerCode, (min=3, max=20) String customerCode, @NotNull @NotNull Item item, Item item, @Min @Min(1) (1) int int quantity) { quantity) { //... //... }
6
05.04.2013 Bean Validation 1.1 – What's cooking? /13
Methodenvalidierung (IV)
- Objektgraphen
- public
public void void placeOrder( placeOrder( @NotNull @NotNull @Size @Size(min=3, max=20) String customerCode, (min=3, max=20) String customerCode, @NotNull @NotNull @Valid @Valid Item item, Item item, @Min @Min(1) (1) int int quantity) { quantity) { //... //... }
7
05.04.2013 Bean Validation 1.1 – What's cooking? /13
Methodenvalidierung (IV)
- Objektgraphen
- Rückgabewerte
public public void void placeOrder( placeOrder( @NotNull @NotNull @Size @Size(min=3, max=20) String customerCode, (min=3, max=20) String customerCode, @NotNull @NotNull @Valid @Valid Item item, Item item, @Min @Min(1) (1) int int quantity) { quantity) { //... //... } @NotNull @NotNull @RetailOrder @RetailOrder @Valid @Valid public public Order placeOrder( Order placeOrder( @NotNull @NotNull @Size @Size(min=3, max=20) String customerCode, (min=3, max=20) String customerCode, @NotNull @NotNull @Valid Item item, @Valid Item item, @Min @Min(1) (1) int int quantity) { quantity) { //... //... }
7
05.04.2013 Bean Validation 1.1 – What's cooking? /13
Methodenvalidierung (V)
- Konstruktoren
- @Valid
@Valid public public OrderService( OrderService(@NotNull @NotNull @Valid @Valid OrderDao orderDao) { OrderDao orderDao) { //... //... }
8
05.04.2013 Bean Validation 1.1 – What's cooking? /13
Methodenvalidierung (V)
- Konstruktoren
- Cross-parameter Constraints
@Valid @Valid public public OrderService( OrderService(@NotNull @NotNull @Valid @Valid OrderDao orderDao) { OrderDao orderDao) { //... //... } @PasswordsMatch @PasswordsMatch public void public void resetPassword( resetPassword(@NotNull @NotNull password, password, @NotNull @NotNull passwordConfirmation) { passwordConfirmation) { ... ... } @SupportedValidationTarget @SupportedValidationTarget(value = ValidationTarget. (value = ValidationTarget.PARAMETERS PARAMETERS) public public class class PasswordsMatchValidator PasswordsMatchValidator implements implements ConstraintValidator< ConstraintValidator<PasswordsMatch PasswordsMatch, Object[]> { , Object[]> { @Override @Override public public void void initialize( initialize(PasswordsMatch PasswordsMatch constraintAnnotation) { constraintAnnotation) { } @Override @Override public public boolean boolean isValid(Object[] value, ConstraintValidatorContext context) { isValid(Object[] value, ConstraintValidatorContext context) { return return value[0].equals(value[1]); value[0].equals(value[1]); } }
8
05.04.2013 Bean Validation 1.1 – What's cooking? /13
EL-Ausdrücke in Fehlermeldungen (I)
- Dynamische Fehlermeldungen mittels Unified EL (JSR 341)
- ValidationMessages.properties:
public public class class Foo { Foo { @DecimalMin @DecimalMin(value= (value="10.0" "10.0", inclusive= , inclusive=true true) private private BigDecimal BigDecimal number number; } javax.validation.constraints.DecimalMax.message = javax.validation.constraints.DecimalMax.message = must must be be less less than than ${inclusive ${inclusive == == true true ? 'or 'or equal equal to to ' : ''}{value} ''}{value}
9
05.04.2013 Bean Validation 1.1 – What's cooking? /13
EL-Ausdrücke in Fehlermeldungen (II)
- Ausgabe des validierten Werts
- public
public class class Shop { Shop { @ValidUser @ValidUser( minAge=18, minAge=18, message= message="User must at least be ${minAge}, but is ${validatedValue.age}." "User must at least be ${minAge}, but is ${validatedValue.age}." ) private private User User user user; //... //... }
10
05.04.2013 Bean Validation 1.1 – What's cooking? /13
EL-Ausdrücke in Fehlermeldungen (II)
- Ausgabe des validierten Werts
- Formatierung mit Formatter-Object
public public class class Shop { Shop { @ValidUser @ValidUser( minAge=18, minAge=18, message= message="User must at least be ${minAge}, but is ${validatedValue.age}." "User must at least be ${minAge}, but is ${validatedValue.age}." ) private private User User user user; //... //... } public public class class Bar { Bar { @Min @Min( value=100, value=100, message= message="Value ${formatter.format('%1$.2f', validatedValue)} is too small" "Value ${formatter.format('%1$.2f', validatedValue)} is too small" ) private private double double number number = 98.12345678d; = 98.12345678d; // ==> "Value 98.12 is too small" // ==> "Value 98.12 is too small" }
10
05.04.2013 Bean Validation 1.1 – What's cooking? /13
Gruppenkonvertierung (I)
- @Valid-Annotation zur Validierung von Objektgraphen
- public
public class class Address { Address { @NotEmpty @NotEmpty(message= message="Street must not be empty "Street must not be empty") ") private private String String street street; } public public class class Customer { Customer { @Valid @Valid private private final final Address Address address address = = new new Address(); Address(); }
11
05.04.2013 Bean Validation 1.1 – What's cooking? /13
Gruppenkonvertierung (I)
- @Valid-Annotation zur Validierung von Objektgraphen
- Fehlertext in Abhängigkeit der Rolle eines Objekts?
public public class class Address { Address { @NotEmpty @NotEmpty(message= message="Street must not be empty "Street must not be empty") ") private private String String street street; } public public class class Customer { Customer { @Valid @Valid private private final final Address Address address address = = new new Address(); Address(); } public public class class Customer { Customer { @Valid @Valid private private final final Address Address homeAddress homeAddress = = new new Address(); Address(); @Valid @Valid private private final final Address Address officeAddress
- fficeAddress =
= new new Address(); Address(); }
11
05.04.2013 Bean Validation 1.1 – What's cooking? /13
Gruppenkonvertierung (II)
- Validierungsgruppen definieren
- @ConvertGroup zur Konvertierung von Gruppen
public public interface interface HomeChecks{} HomeChecks{} public public interface interface OfficeChecks{} OfficeChecks{} public public class class Address { Address { @NotEmpty @NotEmpty.List List({ ({ @NotEmpty @NotEmpty(message= (message="Home street may not be empty" "Home street may not be empty", groups=HomeChecks. , groups=HomeChecks.class class), ), @NotEmpty @NotEmpty(message= (message="Office street may not be empty" "Office street may not be empty", groups=OfficeChecks. , groups=OfficeChecks.class class) }) }) private private String String street street; } public public class class Customer { Customer { @Valid @Valid @ConvertGroup @ConvertGroup(from=Default. (from=Default.class class, to = HomeChecks. , to = HomeChecks.class class) private private Address Address homeAddress homeAddress = = new new Address(); Address(); @Valid @Valid @ConvertGroup @ConvertGroup(from=Default. (from=Default.class class, to = OfficeChecks. , to = OfficeChecks.class class) private private Address Address officeAddress
- fficeAddress =
= new new Address(); Address(); }
12
05.04.2013 Bean Validation 1.1 – What's cooking? /13
Fragen & Antworten
?!
13
05.04.2013 Bean Validation 1.1 – What's cooking? /13
Referenzen
- Alles rund um BV:
http://www.beanvalidation.org/
- JSR 349: “Bean Validation”:
http://jcp.org/en/jsr/detail?id=349
- Hibernate Validator:
http://www.hibernate.org/subprojects/validator.html
- Forum zu Hibernate Validator:
https://forum.hibernate.org/viewforum.php?f=9
- Hibernate Team Blog: http://in.relation.to/
14