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
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

Enterprise AI Trend Report: Gain insights on ethical AI, MLOps, generative AI, large language models, and much more.

2024 Cloud survey: Share your insights on microservices, containers, K8s, CI/CD, and DevOps (+ enter a $750 raffle!) for our Trend Reports.

PostgreSQL: Learn about the open-source RDBMS' advanced capabilities, core components, common commands and functions, and general DBA tasks.

AI Automation Essentials. Check out the latest Refcard on all things AI automation, including model training, data security, and more.

Related

  • Mastering Spring: Synchronizing @Transactional and @Async Annotations With Various Propagation Strategies
  • Composing Custom Annotations in Spring
  • Java, Spring Boot, and MongoDB: Performance Analysis and Improvements
  • Auto Logging in Class and Method Level Using Custom Annotations in Spring Boot App

Trending

  • The Data Streaming Landscape 2024
  • 10 Tips To Improve Python Coding Skills in 2024
  • Implementing Persistence With Clean Architecture
  • Types of Bot Traffic on a Public Internet Website
  1. DZone
  2. Coding
  3. Frameworks
  4. Create Your Own Constraints With Bean Validation 2.0

Create Your Own Constraints With Bean Validation 2.0

Take a look at how you can create and export your own custom constraints for Bean Validation with this step-by-step tutorial.

By 
Hillmer Chona user avatar
Hillmer Chona
·
Jan. 09, 18 · Tutorial
Like (19)
Save
Tweet
Share
105.8K Views

Join the DZone community and get the full member experience.

Join For Free

Data integrity is an important part of application logic. Bean Validation is an API that provides a facility for validating objects, objects members, methods, and constructors. This API allows developers to constrain once, validate everywhere. Bean Validation 2.0 is part of Java EE 8, but it can be used with plain Java SE.

Bean Validation 2.0 brings several built-in constraints, perhaps those are the most common used from small to large applications, some of them are: @NotNull, @Size, @Max, @Min, @Email.

But when built-in constraints are not enough for our applications, we can create our own constraints that can be used everywhere we need it.

Minimum Requirements

  • Java 8
  • Apache Maven 3.3.9 or higher

The Constraint

In our example, we want to constrain that only people over 18 years old can sign up on our website. The constraint must be composed of at least two Java classes: an annotation interface and a validator class. So, we named our constraint Age and our default validator AgeValidator.

The Pom.xml File

To start, we need to define our Maven dependencies. For bean validation, we use validation-api 2.0.0.Final and as our implementation, we use hibernate-validator 6.0.7.Final:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>medellinJUG</groupId>
    <artifactId>my-validator</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <properties>
        <java.ee.version>8.0</java.ee.version>
        <java.se.version>1.8</java.se.version>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <org.hibernate.validator.version>6.0.7.Final</org.hibernate.validator.version>
        <javax.validation.version>2.0.0.Final</javax.validation.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>${javax.validation.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate.validator</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>${org.hibernate.validator.version}</version>
        </dependency>
    </dependencies>

</project>


The Annotation Java Interface

Age will be our annotation type. It is similar to other annotation types. To define this annotation type as a Bean Validation Constraint, we need to add the annotation javax.validation.Constraint (@Constraint) in its declaration.

  • @Target: @Target is where our annotations can be used

  • @Retention:@Retention specifies how the marked annotation is stored. We choose RUNTIME, so it can be used by the runtime environment.

  • @Constraint: @Constraint marks an annotation as being a Bean Validation constraint. The element validatedBy specifies the classes implementing the constraint. We will update this element after we have created the Validator Class.

Our annotation type has four attributes: message, groups, payload, and value, and a nested annotation type: List.

  • String message defines the message that will be showed when the input data is not valid.

  • Class<?>[] groups() lets the developer select to split the annotations into different groups to apply different validations to each group-e.g., @Age(groups=MALE).

  • long value: The value that will be used to define whether the input value is valid or is not- e.g., @Age(value=18).

  • Class<? extends PayLoad> []payLoad(): Payloads are typically used to carry metadata information consumed by a validation client.

  • @interface List: Bean Validation 2.0 provides support for validating container elements by annotating type arguments of parameterized types. To give this characteristic to our constraint, we defined a nested annotation type named List.

import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE_USE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;

@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
@Repeatable(List.class)
@Documented
@Constraint(validatedBy = { })
public @interface Age {

    String message() default "Must be greater than {value}";
    Class<?>[] groups() default { };
    Class<? extends Payload>[] payload() default { };

    long value();

    @Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
    @Retention(RUNTIME)
    @Documented
    @interface List {
        Age[] value();
    }
}


The Java Validator Class

The Validator class must implement ConstraintValidator. It has two methods: initialize and isValid.

The method initialize will be used to establish the necessary attributes to execute the validation — in our case, the age 18 years.

isValid is the method that received the input value and decides whether it is valid or is not.

The implementation of ConstraintValidator<Age, LocalDate> says it accepts Age as an annotation and the input value must be a type of LocalDate:

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.time.Instant;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.Date;

public class AgeValidator implements ConstraintValidator<Age, LocalDate> {

    protected long minAge;

    @Override
    public void initialize(Age ageValue) {
        this.minAge = ageValue.value();
    }

    @Override
    public boolean isValid(LocalDate date, ConstraintValidatorContext constraintValidatorContext) {
        // null values are valid
        if ( date == null ) {
            return true;
        }
        LocalDate today = LocalDate.now();
        return ChronoUnit.YEARS.between(date, today)>=minAge;
    }
}


In order to define the default Validator for our Age Constraint, it is necessary to make a change to the Age annotations class. In our case, we say that AgeValidator is the implementation class for our constraint.

@Constraint(validatedBy = { AgeValidator.class })
public @interface Age {


Using the New Constraint

Now we can use our constraint wherever we need it. As with built-in constraints of Bean Validation, all we need to do is add our constraint to the property we want to validate and let Bean Validation 2.0 do its job.

@Age(value=18)private Date birthDate;


Note: If you want to use the constraint in others projects, you should package it as a JAR file (the interface annotation and the validator class).

That is it! Now you are ready to create your own Bean Validation constraints.

References

  • Bean Validation site http://beanvalidation.org
Spring Framework Annotation

Opinions expressed by DZone contributors are their own.

Related

  • Mastering Spring: Synchronizing @Transactional and @Async Annotations With Various Propagation Strategies
  • Composing Custom Annotations in Spring
  • Java, Spring Boot, and MongoDB: Performance Analysis and Improvements
  • Auto Logging in Class and Method Level Using Custom Annotations in Spring Boot App

Partner Resources


Comments

ABOUT US

  • About DZone
  • Send 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: