Help

With the release of Hibernate Validator 5.1.0.Alpha1 just out, it is time to pick up on the Bean Validation 1.1 spotlight series and cast a light onto method validation. Long time Hibernate Validator users know that method validation is part of Validator since version 4.2, however only as a provider specific featue. Bean Validation 1.1 makes method validation now part of the specification.

But what is method validation? Method validation is the ability to place constraint annotations onto methods or constructors and/or their parameters. Here is an example:

public class User {
     public User(@NotNull @Size(max = 40) String firstName, @NotNull @Size(max = 40) String lastName) {
        // ...
     }

     @NotNull
     @Valid
     public Order placeOrder(@NotNull @Valid Item item) {
          // ...
     }

     @PasswordsMatch
     public void resetPassword( @NotNull String password, @NotNull String passwordConfirmation) {
          // ...
     }

     // ...
}

The constraints describe that whenever the constructor of User is called, firstName and lastName cannot be null and neither can exceed 40 characters. Also, whenever the user places an order, the provided Item instance cannot be null and must be valid. Valid in this context means that the instance itself passes the validation of all its property (constraints placed on fields and getters) and class level constraints. The returned Order instance of the placeOrder() call is a non null instance which also passes all bean constrains for this type. Last but not least, if the user resets his password, the new password and the password confirmation cannot be null and they have to match. The latter is expressed via a so called cross parameter constraint - @PasswordMatch.

Overall, the shown constraints define the pre- and postconditions for a given method or constructor call. This is commonly known as programming by contract which allows to make the specification of the these constraints part of the method. It also avoids code duplication, since these checks don't have to be implemented redundantly in the body of the methods.

But how do these constraints get validated then? Bean Validation offers for this purpose ExecutableValidator which can be retrieved from a Validator instance via Validator.forExecutables(). This ExecutableValidator offers the methods to validate method/constructor parameters and return values. This in itself, however, is not very helpful for an application developer. She would have to write the required code to handle the validation herself which is not a trivial task. Instead the intention is that frameworks and libraries provide the integration for the application developer via some sort of AOP, interceptor or proxy based approach. That way, method validation occurs transparently upon invocation of constrained methods or constructors, throwing a ConstraintViolationException whenever one more more constraints are violated. An example of this type of integration is the Java EE 7 framework.

In Java EE 7 all CDI managed beans are automatically method validated. All you have to do is to place constraints on methods or constructors and their parameters. CDI will then, via its interceptor capabilities, evaluate all method validation constraints. In this context it is important to know that Bean Validation does not validate getters (method name starts with get, has a return type and no parameters or starts with is, is returning boolean and has no parameters) per default. This is to avoid conflicts with the validation of bean constraints. This behaviour can be configured via the use of @ValidateOnExecution or in validation.xml using default-validated-executable-types. The specification contains all the details and also gives some examples.

Last but not least, another caveat. When using method validation constraints within class hierarchies, the specification demands that the Liskov substitution principle holds. Formally this means that a method's preconditions (as represented by parameter constraints) must not be strengthened and its postconditions (as represented by return value constraints) must not be weakened in sub-types. Concretely it implies that in sub-types no parameter constraints can be declared on overridden or implemented methods. Also parameters cannot be marked for cascaded validation. Instead, all parameter constraints must be defined at the method's root within the hierarchy. The Bean Validation implementation will throw a ConstraintDeclarationException if the Liskov substitution principle is violated. The complete set of rules can be found in Method constraints in inheritance hierarchies of the specification.

I hope this blog helped to shine some light on the biggest new feature of Bean Validation 1.1 - method validation. If you have questions, leave a comment, contact us via the forum or chat to us in IRC.

Happy validating!

P.S. We will talk about the changes to the metadata and javax.validation.Path API related to method validation in another post. We also will have a closer look at the details of implementing cross parameter constraints. Stay tuned.

20 comments:
18. May 2014, 13:58 CET | Link

The Texas commercial real estate brokerage industry has changed a lot over the past 10-15 years especially in major cities like Houston, Dallas, Austin, and San Antonio. These are Commercial Realty Investments opinions and they will not be popular with competing brokerage companies! http://www.healthybodyinc.com/rice-phytoceramide-gluten-free-and-clinically-proven/

ReplyQuote
07. Jun 2014, 16:46 CET | Link

Luckily for you there are other ways for you to get free stuff online. Using coupons for free stuff is one of the great ways to save money on products that you find on the Internet. Often times, organizations use these coupons to offer their clients free merchandise for trial use.freebies

09. Jun 2014, 10:08 CET | Link

Actual product packaging and materials may contain more and different information than what is shown on our website. We recommend that you do not rely solely on the information presented and that you always read labels, warnings, and directions before using or consuming a product. Please see our full disclaimer below. amazon.com

10. Jun 2014, 06:50 CET | Link

Actual product packaging and materials may contain more and different information than what is shown on our website. We recommend that you do not rely solely on the information presented and that you always read labels, warnings, and directions before using or consuming a product. Please see our full disclaimer below. amazon.com

11. Jun 2014, 07:19 CET | Link

Learn everything you need to know about the program so you can decide if Unlock His Heart: Shortcut To His Love is the right choice for you before you buy it.guide

11. Jun 2014, 18:42 CET | Link

My name is Abi. I run a local e-commerce website in Sri Lanka, and it gets over 1500 unique visitors a day. It means a lot that the traffic I get everyday converts well.web hosting

 
17. Jun 2014, 12:26 CET | Link

wow it's so constructive and make up my mind to stand up and do different than others. newamericanjackets

18. Jun 2014, 17:04 CET | Link
Adam99

I am satisfied to find this article very useful for me, as it contains lot of valuable information. I always prefer to read the quality content and this thing I found in you publication. Thanks for sharing. Greetings from download cracks

 
21. Jun 2014, 16:15 CET | Link

The forex market is the biggest most liquid market in the world by far. This market is open for 24 hours from Monday to Friday, and it is a worldwide market that is not country bound. forex Currency prices and exchange rates are determined mainly by supply and demand. They are fluid, constantly in motion with the ebb and flow of the various global economic and financial markets forex trading

26. Jun 2014, 16:04 CET | Link

Boost Your Bust by Jenny Bolton currently ranks 1 for Breast Enhancement Guides in the Clickbank marketplace beating out competitors like The Enhanced Breast Enlargement Program and the 10 Best Kept Secrets To Natural Breast Enlargement (both of which I do NOT recommend).on www RebelMouse

12. Jul 2014, 07:48 CET | Link

Currently, Daryl is Co-CA for the Asian BP 2013 hosted by Beijing Aeronautical and Astronautical University. venus factor reviews

13. Jul 2014, 18:29 CET | Link

This site is a leading resource for information about the Jeff Martin Heartburn No More PDF book that teaches you unique and rare tips on how to eliminate heartburn and cure acid reflux in as little as 2 days.look for it on rebelmouse

 
14. Jul 2014, 10:19 CET | Link
United States

Hawaii is expensive when you come from the southern United States). Because this was a long time ago, the Scripting Wife was not as Internet savvy as she is today. drug lawyer

 
15. Jul 2014, 14:27 CET | Link
instructions

Click HELP for text formatting instructions. Then ediA trading week starts on Sunday and goes through Friday. Trading starts in Sydney, Australia, and continues around the globe to Tokyo, London, and finally New York. the venus factort this text and check the preview.

17. Jul 2014, 08:55 CET | Link

While there are many benefits of Charlotte SEO services the following are most important for businesses. Our Charlotte marketing agency specializes in SEO to make your work easy as a business enterprise.charlotte seo company

 
17. Jul 2014, 09:34 CET | Link
christi
It's a very useful and interesting site. Thanks! <a href='http://www.hermesu.com'>hermes replica</a>
 
17. Jul 2014, 09:36 CET | Link
christi
It's a very useful and interesting site. Thanks! [hermes replica=>http://www.hermesu.com]
18. Jul 2014, 17:27 CET | Link

This site is a leading resource for information about the Carlos Cavallo Forever Yours PDF book and guide to understanding men that teaches you why men pull away and how to get a man to open up and communicate with you on a deep emotional level.https://www.rebelmouse.com/foreveryours/

21. Jul 2014, 18:51 CET | Link

This site is a leading resource for information about the Carrie Engel Innocent Words That Drive Men Wild PDF book and attraction system that teaches you how to use innocent words to grab a man's attention, capture his heart, and make him completely loyal to you.www rebelmouse

22. Jul 2014, 19:05 CET | Link

This Text Your Ex Back review examines the Michael Fiore PDF and its ability to help you get your ex back using tiny text messages sent from your cell phone.http://www.textyourexback2.com/

Post Comment