Spring3.1 new support for Bean Validation specification (method level validation)

Source: Internet
Author: User

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
  1. Public class Usermodel {
  2. @NotNull (Message = "User.username.null")
  3. @Pattern (regexp = " [a-za-z0-9_]{5,10}", message = "User.username.illegal")
  4. Private String username;
  5. @Size (min = 5, max=, message = "Password.length.illegal")
  6. Private String password;
  7. //Omit Setter/getter
  8. }

2. Enable Dependency Injection validation support (Spring-config-bean-validator.xml)

Java code
    1. <!--registered Bean authentication after processor--
    2. <bean Class="Org.springframework.validation.beanvalidation.BeanValidationPostProcessor"/ >

3. The bean's XML configuration definition (Spring-config-bean-validator.xml)

Java code
    1. <bean id="User" class="Com.sishuok.validator.UserModel">
    2. <property name="username" value="@"/>
    3. <property name="password" value="#"/>
    4. </bean>

4. Test Cases

Java code
  1. @RunWith (value = Springjunit4classrunner.) class)
  2. @ContextConfiguration (value = {"classpath:spring-config-bean-validator.xml"})
  3. Public class beanvalidatortest {
  4. @Autowired
  5. Usermodel user;
  6. @Test
  7. Public void Test () {
  8. }
  9. }

5. After running the test, the container fails to start and you will see the following exception:

Java code
  1. java.lang.IllegalStateException:Failed to load ApplicationContext
  2. ......
  3. 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
  4. ......
  5. 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
  1. Public Usermodel get (Integer uuid) {
  2. //front-facing conditions
  3. Assert.notnull (UUID);
  4. Assert.istrue (uuid > 0, "UUID must lt 0");
  5. //Get User Model
  6. Usermodel user = new Usermodel (); //should be obtained from the database here
  7. //Post conditions
  8. Assert.notnull (user);
  9. return user;
  10. }

Pre-conditions and post-condition writing are very annoying tasks.

With Methodvalidationpostprocessor , we can verify this:

Java code
  1. Public @NotNull Usermodel Get2 (@NotNull @Size(min = 1) Integer uuid) {
  2. //Get User Model
  3. Usermodel user = new Usermodel (); //should be obtained from the database here
  4. return user;
  5. }

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
  1. @Validated //① tells Methodvalidationpostprocessor that this bean needs to turn on method level validation support
  2. Public class UserService {
  3. Public @NotNull Usermodel Get2 (@NotNull @Min(value = 1) Integer uuid) { //② declaration preconditions/Post conditions
  4. //Get User Model
  5. Usermodel user = new Usermodel (); //should be obtained from the database here
  6. if (Uuid > +) {//Make it easy to add the judgment (assuming that the incoming uuid>100 returns null)
  7. return null;
  8. }
  9. return user;
  10. }
  11. }

2. Turn on Spring3.1 to method level validation support (Spring-config-method-validator.xml)

Java code
    1. <!--registration method verified after processor--
    2. <bean Class="Org.springframework.validation.beanvalidation.MethodValidationPostProcessor"/ >

3. The bean's XML configuration definition (Spring-config-method-validator.xml)

Java code
    1. <bean id="UserService" class="Com.sishuok.validator.UserService"/>

4. Test Cases

Java code
  1. @RunWith (value = Springjunit4classrunner.) class)
  2. @ContextConfiguration (value = {"classpath:spring-config-method-validator.xml"})
  3. Public class methodvalidatortest {
  4. @Autowired
  5. UserService UserService;
  6. @Test
  7. Public void testconditionsuccess () {//① normal process
  8. Userservice.get2 (1);
  9. }
  10. @Test (expected = org.hibernate.validator.method.MethodConstraintViolationException.) class)
  11. Public void Testprecondtionfail () { //② bad uuid (i.e., precondition not satisfied)
  12. Userservice.get2 (0);
  13. }
  14. @Test (expected = org.hibernate.validator.method.MethodConstraintViolationException.) class)
  15. Public void Testpostcondtionfail () { //③ does not meet the return value of the post condition
  16. Userservice.get2 (10000);
  17. }
  18. }

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.