DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How Spring and Hibernate Simplify Web and Database Management
  • Querydsl vs. JPA Criteria, Part 6: Upgrade Guide To Spring Boot 3.2 for Spring Data JPA and Querydsl Project
  • Upgrade Guide To Spring Boot 3.0 for Spring Data JPA and Querydsl
  • Getting Started With JPA/Hibernate

Trending

  • Blue Skies Ahead: An AI Case Study on LLM Use for a Graph Theory Related Application
  • DGS GraphQL and Spring Boot
  • Start Coding With Google Cloud Workstations
  • The Cypress Edge: Next-Level Testing Strategies for React Developers
  1. DZone
  2. Coding
  3. Frameworks
  4. Method Validation With Spring 3.1 and Hibernate Validator 4.2

Method Validation With Spring 3.1 and Hibernate Validator 4.2

JSR 303 and Hibernate Validator have been awesome additions to the Java ecosystem, giving you a standard way to validate your domain model across application layers.

By 
Gunnar Hillert user avatar
Gunnar Hillert
·
Jan. 13, 12 · Tutorial
Likes (0)
Comment
Save
Tweet
Share
32.5K Views

Join the DZone community and get the full member experience.

Join For Free

JSR 303 and Hibernate Validator have been some awesome additions to the Java ecosystem, giving you a standard way to validate your domain model across application layers. Combined with the annotations of the Java Persistence API (JPA) you have some very nice tools at your disposal to ensure that only valid data enters your database.

However, one piece of missing functionality was the ability to also validate method calls. For example, wouldn't it be nice if you could use normal JSR 303 annotations to safeguard business layer calls as well?

Of course you can enforce constraints programmatically, e.g. prevent the passing of Null parameters. Spring for instance provides the org.springframework.util.Assert class. However, it would be desirable, if constraints placed on input parameters as well as return values were part of the method contract.

Enter Hibernate Validator 4.2, which was released in June of 2011. It provides now method validation and Gunnar Morling, one of the committers, has an excellent write-up on this on his blog at:

  • http://musingsofaprogrammingaddict.blogspot.com/2011/01/method-validation-with-hibernate.html

Also, check out the Hibernate validator documentation regarding method validation. Gunnar Morling also provides some preliminary Spring support available at GitHub:

  • https://github.com/gunnarmorling/methodvalidation-integration

But the news for Spring aficionados is getting even better - Direct support for Method Validation With Hibernate Validator is now available in the lastest Spring 3.1 release that went GA just two weeks ago.

Specifically Spring 3.1 provides the following support in regards to method validation:

  • org.springframework.validation.beanvalidation.MethodValidationInterceptor
  • org.springframework.validation.beanvalidation.MethodValidationPostProcessor

In order to get started, make sure that you are using Spring 3.1.0.RELEASE and that you have Hibernate Validator 4.2 in your classpath. That's all what you need to begin using JSR 303 annotations on the method level. For example, now you can annotate your methods using e.g.:


@Validated
public interface BusinessService {
    @NotNull String convertToUpperCase(@NotEmpty String input);
}

The @Validated Annotation indicates that the methods in the class are to be included for method validation. Keep in mind that you can specify your own annotation that will be enabling method level validation for the annotated class. Specify your own annotation by calling setValidatedAnnotationType on the MethodValidationPostProcessor.

However, placing the annotations themselves will not enforce the constraints 'automagically'. In fact Spring will be using AOP (Aspect Oriented Programming) Advices under the covers that delegate to Hibernate Validator. The easiest way to enable these advices is to declare a MethodValidationPostProcessor bean in your Spring application context as shown below.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

 <context:component-scan base-package="com.hillert.spring.validation" />

    <bean id="validator"
      class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>

    <bean class="org.springframework.validation.beanvalidation.MethodValidationPostProcessor"/>

</beans>

For more details, I have published a small project over at GitHub that illustrates method level validation using Hibernate Validator:

  • https://github.com/ghillert/spring-hibernate-validator-sample 

In order to get get started:

  1. Clone the repository using $ git clone git://github.com/ghillert/spring-hibernate-validator-sample.git 
  2. $ cd spring-hibernate-validator-sample
  3. Build the sample using Maven $ mvn clean package
  4. Run it with $ mvn exec:java

The command-line based sample provides a simple String conversion service, that converts Strings to upper-case. You can insert those Strings from the command line. The Service layer will enforce the following constraints using method level Hibernate Validator annotations:

  • The input String must not be empty (not null and not an empty String)
  • The conversion service will never return null

In order to trigger validation exceptions you can enter some special strings:

  • Pressing just enter (no string entered) will cause an empty String parameter to be set
  • Submitting "null" (The String), will cause a null parameter to be set
  • When entering "returnnull", the underlying business method will return Null

The Main method will catch the occurring MethodConstraintViolationExceptions and print some details to the command prompt.

Lastly, the current method validator support via Spring is specifically targetting Hibernate Validator. However, there are standardization efforts underway as part of the Bean Validation 1.1 specification (JSR-349). In order to follow the progress, please follow also http://beanvalidation.org/.

Spring will provide support for JSR-349 as soon as the official standard has been ratified. In order to track inclusion into the Spring framework, please follow also Spring Framework Jira ticket SPR-8199 . As of today this feature should be available in the next Spring 3.2 release.

I hope this blog entry and the accompanying sample have showed you how easy it is to get started with  method level validation using Spring and Hibernate Validator. Please let me know if you have further questions or run into issues.

From http://hillert.blogspot.com/2011/12/method-validation-with-hibernate.html

Spring Framework Hibernate

Opinions expressed by DZone contributors are their own.

Related

  • How Spring and Hibernate Simplify Web and Database Management
  • Querydsl vs. JPA Criteria, Part 6: Upgrade Guide To Spring Boot 3.2 for Spring Data JPA and Querydsl Project
  • Upgrade Guide To Spring Boot 3.0 for Spring Data JPA and Querydsl
  • Getting Started With JPA/Hibernate

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!