I. Introduction to bean Validation Framework write bean Validation standardizes constraint definition, declaration and Validation for the Java PLATFO Rm.
The general meaning is: Bean Validation standardizes the definition, description, and validation of constraints on the Java platform.
For more information, please refer to: http://beanvalidation.org/
Bean validation now has two specifications:
1. Bean Validation 1.0 (JSR-303)
Wrote this JSR would define a meta-data model and API for JAVABEANTM validation based on annotations, with overrides and extend Ed Meta-data through the use of the XML validation descriptors.
The annotation-based JavaBean validation metadata model and API are defined, and metadata definitions can be made through XML, but annotations overwrite the metadata definition of the XML.
For more information, please refer to: http://jcp.org/en/jsr/detail?id=303
JSR-303 is primarily a validation of the JavaBean , such as the method level (method parameter / return value), dependency injection, etc. validation is not specified. Therefore, there is the JSR-349 norm of production.
2. Bean Validation 1.1 (JSR-349)
Wrote bean Validation standardizes constraint definition, declaration and Validation for the Java platform.
Bean Validation standardizes The definition, description, and validation of constraints on the Java platform.
This specification is currently in draft State, for more information please refer to: http://jcp.org/en/jsr/detail?id=349.
The main content of the draft is now:
Method-level validation support (validating method parameters and return values);
Support for Dependency injection validation.
For a detailed introduction to bean validation, refer to the Bean Validation official website to view http://beanvalidation.org/.
Spring3.1 has now fully supported support for dependency injection validation and method-level validation, but is not native (specification or draft).
The reference implementation of Bean Validation 1.0 has hibernate Validator (: http://www.hibernate.org/subprojects/validator.html); 1.1 is still in draft state.
Ii. location of Bean validation in development
From the Hibernate validator reference documentation, you can see that we can implement validation in any location.
1, the performance layer verification: SPRINGMVC provides the performance layer verification of JSR-303;
2, Business Logic Layer verification: Spring3.1 provides method validation of the business Logic layer (of course validation can occur on other layers, but I think the method validation should validate the business logic);
3. DAO Layer Verification: Hibernate provides validation of model data for the DAO layer (refer to 7.3 of Hibernate validator reference documentation. ORM integration).
4, database-side verification: Through the database constraints;
5, Client authentication support: JSR-303 also provides programmatic validation support.
For DAO layer and client validation support is not in our sample scope, ignore, interested students can refer to "Hibernate Validator Reference" (Chinese).
In the test support you need to prepare the following jar packages:
Validation-api-1.0.0.ga.jar
Hibernate-validator-4.2.0.final.jar
Iv. Spring3.0 support for performance layer validation
Refer to my latest SPRINGMVC + spring3.1.1 + hibernate4.1.0 Integration and FAQs Summary or SPRINGMVC use JSR-303 for verification @Valid.
Not elaborated here.
V. Spring3.0 support for Dependency injection validation (draft Bean Validation 1.1)
SPRING3.0 began to support the validation of dependency injection dependencies. Spring's support for dependency injection validation is referenced in the "Spring open/Closed principle Performance-beanpostprocessor extension Point-2" in Beanvalidationpostprocessor.
Example:
1. Bean Component Class definition
Java code
- Public class Usermodel {
- @NotNull (Message = "User.username.null")
- @Pattern (regexp = " [a-za-z0-9_]{5,10}", message = "User.username.illegal")
- Private String username;
- @Size (min = 5, max=, message = "Password.length.illegal")
- Private String password;
- //Omit Setter/getter
- }
2. Enable Dependency Injection validation support (Spring-config-bean-validator.xml)
Java code
- <!--registered Bean authentication after processor--
- <bean Class="Org.springframework.validation.beanvalidation.BeanValidationPostProcessor"/ >
3. The bean's XML configuration definition (Spring-config-bean-validator.xml)
Java code
- <bean id="User" class="Com.sishuok.validator.UserModel">
- <property name="username" value="@"/>
- <property name="password" value="#"/>
- </bean>
4. Test Cases
Java code
- @RunWith (value = Springjunit4classrunner.) class)
- @ContextConfiguration (value = {"classpath:spring-config-bean-validator.xml"})
- Public class beanvalidatortest {
- @Autowired
- Usermodel user;
- @Test
- Public void Test () {
- }
- }
5. After running the test, the container fails to start and you will see the following exception:
Java code
- java.lang.IllegalStateException:Failed to load ApplicationContext
- ......
- caused by:org.springframework.beans.factory.BeanCreationException:Error creating bean with Name ' user ' Defined in class path resource [Spring-config-bean-validator.xml]: Initialization of Bean failed; Nested exception is Org.springframework.beans.factory.BeanInitializationException:Bean state is Invalid:password- Password.length.illegal; Username-user.username.illegal
- ......
- caused By:org.springframework.beans.factory.BeanInitializationException:Bean is Invalid:password- Password.length.illegal; Username-user.username.illegal
We can see that the user name verification failed.
Vi. Spring3.1 Support Method level validation (draft Bean Validation 1.1)
Spring3.1 started to support method-level validation. Spring support for method-level validation is available in the "Spring open/Closed principle Performance-beanpostprocessor extension Point-2" in Methodvalidationpostprocessor.
With method-level validation, we are able to make contractual designs more simple in the Java world, with reference to "building error-Free software: An Introduction to contractual design" for contract design.
We can verify this without methodvalidationpostprocessor before:
Java code
- Public Usermodel get (Integer uuid) {
- //front-facing conditions
- Assert.notnull (UUID);
- Assert.istrue (uuid > 0, "UUID must lt 0");
- //Get User Model
- Usermodel user = new Usermodel (); //should be obtained from the database here
- //Post conditions
- Assert.notnull (user);
- return user;
- }
Pre-conditions and post-condition writing are very annoying tasks.
With Methodvalidationpostprocessor , we can verify this:
Java code
- Public @NotNull Usermodel Get2 (@NotNull @Size(min = 1) Integer uuid) {
- //Get User Model
- Usermodel user = new Usermodel (); //should be obtained from the database here
- return user;
- }
Validation of preconditions: implementation through bean Validation annotations on the parameters of the method;
Validation of the Post condition: implemented directly on the return value via the bean validation annotation.
Very good, very good, since then we can do more perfect contract programming in the Java World.
Example:
1. Service class definition
Java code
- @Validated //① tells Methodvalidationpostprocessor that this bean needs to turn on method level validation support
- Public class UserService {
- Public @NotNull Usermodel Get2 (@NotNull @Min(value = 1) Integer uuid) { //② declaration preconditions/Post conditions
- //Get User Model
- Usermodel user = new Usermodel (); //should be obtained from the database here
- if (Uuid > +) {//Make it easy to add the judgment (assuming that the incoming uuid>100 returns null)
- return null;
- }
- return user;
- }
- }
2. Turn on Spring3.1 to method level validation support (Spring-config-method-validator.xml)
Java code
- <!--registration method verified after processor--
- <bean Class="Org.springframework.validation.beanvalidation.MethodValidationPostProcessor"/ >
3. The bean's XML configuration definition (Spring-config-method-validator.xml)
Java code
- <bean id="UserService" class="Com.sishuok.validator.UserService"/>
4. Test Cases
Java code
- @RunWith (value = Springjunit4classrunner.) class)
- @ContextConfiguration (value = {"classpath:spring-config-method-validator.xml"})
- Public class methodvalidatortest {
- @Autowired
- UserService UserService;
- @Test
- Public void testconditionsuccess () {//① normal process
- Userservice.get2 (1);
- }
- @Test (expected = org.hibernate.validator.method.MethodConstraintViolationException.) class)
- Public void Testprecondtionfail () { //② bad uuid (i.e., precondition not satisfied)
- Userservice.get2 (0);
- }
- @Test (expected = org.hibernate.validator.method.MethodConstraintViolationException.) class)
- Public void Testpostcondtionfail () { //③ does not meet the return value of the post condition
- Userservice.get2 (10000);
- }
- }
With the above test, we can see that Spring3.1 has very good support for contract programming.
Note that when you use method-level validation:
1, because Bean Validation1.1 is in the draft state, Spring3.1 can not support the native bean Validation1.1, will be used in the future of the Bean Validation1.1 published directly using the native.
2, Spring3.1 need to use Hibernate Validator 4.2 and later.
Let's look forward to the release of Bean Validation 1.1.
Spring3.1 new support for the Bean Validation specification (method-level validation)