eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Partner – LambdaTest – NPI EA (cat=Testing)
announcement - icon

Regression testing is an important step in the release process, to ensure that new code doesn't break the existing functionality. As the codebase evolves, we want to run these tests frequently to help catch any issues early on.

The best way to ensure these tests run frequently on an automated basis is, of course, to include them in the CI/CD pipeline. This way, the regression tests will execute automatically whenever we commit code to the repository.

In this tutorial, we'll see how to create regression tests using Selenium, and then include them in our pipeline using GitHub Actions:, to be run on the LambdaTest cloud grid:

>> How to Run Selenium Regression Tests With GitHub Actions

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

1. Introduction

Yavi is a Java validation library that allows us to easily and cleanly ensure that our objects are in a valid state.

Yavi is an excellent lightweight choice for object validation within Java applications. It doesn’t rely on reflection or adding additional annotations to the objects being validated, so it can be used entirely separately from the classes we wish to validate. It also emphasizes a type-safe API, ensuring we can’t accidentally define impossible validation rules. In addition, it has full support for any types that we can define in our application, as well as having a large range of predefined constraints to rely on whilst still allowing us to easily define our own where necessary.

In this tutorial, we’re going to have a look at Yavi. We’ll see what it is, what we can do with it, and how to use it.

2. Dependencies

Before using Yavi, we need to include the latest version in our build, which is 0.14.1 at the time of writing.

If we’re using Maven, we can include this dependency in our pom.xml file:

<dependency>
    <groupId>am.ik.yavi</groupId>
    <artifactId>yavi</artifactId>
    <version>0.14.1</version>
</dependency>

At this point, we’re ready to start using it in our application.

3. Simple Validations

Once we’ve got Yavi available in our project, we’re ready to start using it to validate our objects.

The simplest validators that we can build are for simple value types such as String or Integer. Each of the supported types is constructed using a builder class found in the am.ik.yavi.builder package:

StringValidator<String> validator = StringValidatorBuilder.of("name", c -> c.notBlank())
  .build();

This constructs a validator that we can use to validate String instances to ensure they’re not blank. The first parameter to the builder is a name for the value we’re validating, and the second is a lambda that defines the validation rules to apply.

More often though, we want to validate an entire bean, not just a single value. Validators for these are built using the ValidatorBuilder instead, to which we can add multiple rules for different fields:

public record Person(String name, int age) {}
Validator<Person> validator = ValidatorBuilder.of(Person.class)
  .constraint(Person::name, "name", c -> c.notBlank())
  .constraint(Person::age, "age", c -> c.positiveOrZero().lessThan(150))
  .build();

Every constraint() call adds a constraint to our validator for a different field. The first parameter to this is the getter for the field, which must be a method on the type we’re validating. The third parameter is then a lambda for defining the constraint, the same as before. Yavi ensures that this is suitable for the return type of our getter method. For example, we can use notBlank() on a String field but not an integer field.

Once we’ve got our validator, we can use it to validate appropriate objects:

ConstraintViolations result = validator.validate(new Person("", 42));
assertFalse(result.isValid());

This returned ConstraintViolations object tells us whether or not the provided object is valid, and if it’s invalid we can see what the actual violations are:

assertEquals(1, result.size());
assertEquals("name", result.get(0).name());
assertEquals("charSequence.notBlank", result.get(0).messageKey());

Here we can see that the name field is invalid and that the violation is because it shouldn’t be blank.

3.1. Validating Nested Objects

Often our beans that we want to validate have other beans within them, and we want to ensure these are also valid. We can achieve this using the nest() method of our builder instead of the constraint() call:

public record Name(String firstName, String surname) {}
public record Person(Name name, int age) {}

Validator<Name> nameValidator = ValidatorBuilder.of(Name.class)
  .constraint(Name::firstName, "firstName", c -> c.notBlank())
  .constraint(Name::surname, "surname", c -> c.notBlank())
  .build();

Validator<Person> personValidator = ValidatorBuilder.of(Person.class)
  .nest(Person::name, "name", nameValidator)
  .constraint(Person::age, "age", c -> c.positiveOrZero().lessThan(150))
  .build();

Once defined, we can use this the same as before. Now though, Yavi will automatically compose the names of any violations using dotted notation so that we can see exactly what’s happened:

assertEquals(2, result.size());
assertEquals("name.firstName", result.get(0).name());
assertEquals("name.surname", result.get(1).name());

Here we’ve got our two expected violations – one on name.firstName and the other on name.surname. These tell us that the fields in question are nested within the name field of the outer object.

3.2. Cross-Field Validations

In some cases, we can’t validate a single field in isolation. The validation rules might depend on the values of other fields in the same object. We can achieve this using the constraintOnTarget() method, which validates the provided object and not a single field of it:

record Range(int start, int end) {}

Validator<Range> validator = ValidatorBuilder.of(Range.class)
  .constraintOnTarget(range -> range.end > range.start, "end", "range.endGreaterThanStart",
    "\"end\" must be greater than \"start\"")
  .build();

In this case, we’re ensuring that the end value of our range is greater than the start value. When doing this, we need to provide some extra values since we’re effectively creating a custom constraint.

Unsurprisingly, using this validator is the same as before. However, because we’ve defined the constraint ourselves we’ll get our custom values through in the violation:

assertEquals(1, result.size());
assertEquals("end", result.get(0).name());
assertEquals("range.endGreaterThanStart", result.get(0).messageKey());

4. Custom Constraints

Most of the time, Yavi provides us with all the constraints that we need for validating our objects. However, in some cases, we might need something that isn’t covered by the standard set.

We saw earlier an example of writing a custom constraint inline by providing a lambda. We can do similar within our constraint builder to define a custom constraint for any field:

Validator<Data> validator = ValidatorBuilder.of(Data.class)
  .constraint(Data::palindrome, "palindrome",
    c -> c.predicate(s -> validatePalindrome(s), "palindrome.valid", "\"{0}\" must be a palindrome"))
  .build();

Here we’ve used the predicate() method to provide our lambda, as well as giving it a message key and default message. This lambda can do anything we want, as long as it fits the definition of java.util.function.Predicate<T>. In this case, we’re using a function that checks if a string is a palindrome or not.

Sometimes though we might want to write our custom constraint in a more reusable manner, we’re able to do this by creating a class that implements the CustomConstraint interface:

class PalindromeConstraint implements CustomConstraint<String> {
    @Override
    public boolean test(String input) {
        String reversed = new StringBuilder()
          .append(input)
          .reverse()
          .toString();

        return input.equals(reversed);
    }

    @Override
    public String messageKey() {
        return "palindrome.valid";
    }

    @Override
    public String defaultMessageFormat() {
        return "\"{0}\" must be a palindrome";
    }
}

Functionally this is the same as our lambda, only as a class we can more easily reuse it between validators. In this case, we need only pass an instance of this to our predicate() call and everything else is configured for us:

Validator<Data> validator = ValidatorBuilder.of(Data.class)
  .constraint(Data::palindrome, "palindrome", c -> c.predicate(new PalindromeConstraint()))
  .build();

Whichever of these methods we use, we can use the resulting validator exactly as expected:

ConstraintViolations result = validator.validate(new Data("other"));
assertFalse(result.isValid());
assertEquals(1, result.size());
assertEquals("palindrome", result.get(0).name());
assertEquals("palindrome.valid", result.get(0).messageKey());

Here we can see that our field is invalid and that the result includes our defined message key to indicate exactly what was wrong with it.

5. Conditional Constraints

Not all constraints make sense to be applied in all cases. Yavi gives us some tools to configure some constraints to only work in some cases.

One option that we have is to provide a context to the validator. We can define this as any type that we want, as long as it implements the ConstraintGroup interface, though an enum is a very convenient option:

enum Action implements ConstraintGroup {
    CREATE,
    UPDATE,
    DELETE
}

We can then define a constraint using the constraintOnCondition() wrapper to define a constraint that only applies under a particular context:

 Validator<Person> validator = ValidatorBuilder.of(Person.class)
  .constraint(Person::name, "name", c -> c.notBlank())
  .constraintOnCondition(Action.UPDATE.toCondition(),
    b -> b.constraint(Person::id, "id", c -> c.notBlank()))
  .build();

This will always validate that the name field isn’t blank, but will only validate that the id field isn’t blank if we provide a context of UPDATE.

When using this, we need to validate slightly differently, by providing the context along with the value we’re validating:

ConstraintViolations result = validator.validate(new Person(null, "Baeldung"), Action.UPDATE);
assertFalse(result.isValid());

If we want to have even more control, the constraintOnCondition() method can take a lambda that accepts the value being validated and the context, and indicates if the constraint should be applied. This allows us to define whatever conditions we want:

Validator<Person> validator = ValidatorBuilder.of(Person.class)
  .constraintOnCondition((person, ctx) -> person.id() != null,
    b -> b.constraint(Person::name, "name", c -> c.notBlank()))
  .build();

In this case, the name field will only be validated if the id field has a value:

ConstraintViolations result = validator.validate(new Person(null, null));
assertTrue(result.isValid());

6. Argument Validation

One of Yavi’s unique points is its ability to wrap method calls in validation, ensuring that the arguments are valid before calling the method.

Argument validators are all built using the ArgumentsValidatorBuilder builder class. To ensure type safety, this constructs one of 16 possible types, supporting between 1 and 16 arguments to the method.

This is especially useful to wrap the call to the constructor. This allows us to guarantee valid arguments before calling the constructor, instead of constructing a potentially invalid object and validating it afterwards:

Arguments2Validator<String, Integer, Person> validator = ArgumentsValidatorBuilder.of(Person::new)
  .builder(b -> b
    ._string(Arguments1::arg1, "name", c -> c.notBlank())
    ._integer(Arguments2::arg2, "age", c -> c.positiveOrZero())
  )
  .build();

The slightly unusual syntax of _string() and _integer() are so the compiler knows the type to use for each argument.

Once we’ve built our validator, we can then call it passing in all of the appropriate arguments:

Validated<Person> result = validator.validate("", -1);

This result tells us if the arguments were valid, and if not then returns the validation errors:

assertFalse(result.isValid());
assertEquals(2, result.errors().size());
assertEquals("name", result.errors().get(0).name());
assertEquals("charSequence.notBlank", result.errors().get(0).messageKey());
assertEquals("age", result.errors().get(1).name());
assertEquals("numeric.positiveOrZero", result.errors().get(1).messageKey());

If the arguments were all valid then we can instead get back the result of our method – in this case, the constructed object:

assertTrue(result.isValid());
Person person = result.value();

We can also use this same technique to wrap methods on objects as well:

record Person(String name, int age) {
    boolean isOlderThan(int check) {
        return this.age > check;
    }
}
Arguments2Validator<Person, Integer, Boolean> validator = ArgumentsValidatorBuilder.of(Person::isOlderThan)
  .builder(b -> b
    ._integer(Arguments2::arg2, "age", c -> c.positiveOrZero())
  )
  .build();

This will validate the arguments on the method call and only call the method if they’re all valid. In this case, we pass the instance we’re calling the method on as the first argument and then pass all other arguments afterward:

Person person = new Person("Baeldung", 42);
Validated<Boolean> result = validator.validate(person, -1);

As before, if the arguments pass validation then Yavi calls the method and we can access the return value. If the arguments fail validation, it never calls the wrapped method and instead returns the validation errors.

7. Annotation Processing

So far, Yavi has been rather repetitive in several places. For example, we’ve needed to specify the field name and the method reference to get the value, which typically has the same name. Yavi comes with a Java annotation processor that will help here.

7.1. Annotating Fields

We can annotate fields on our objects with the @ConstraintTarget annotation to automatically generate some meta classes:

record Person(@ConstraintTarget String name, @ConstraintTarget int age) {}

These annotations can go on constructor arguments, getters, or fields and it will work the same.

We can then use these generated classes when we’re building our validator:

Validator<Person> validator = ValidatorBuilder.of(Person.class)
  .constraint(_PersonMeta.NAME, c -> c.notBlank())
  .constraint(_PersonMeta.AGE, c -> c.positiveOrZero().lessThan(150))
  .build();

We no longer need to specify both the field name and the corresponding getter. In addition, if we try to use a field that doesn’t exist then this will no longer compile.

Once built, this validator is identical to before and can used the same as before.

7.2. Annotating Arguments

We can also use the same technique for method arguments when using the support for wrapping method calls. In this case, we use the @ConstraintArguments annotation instead, annotating the method or constructor that we plan on validating:

record Person(String name, int age) {
    @ConstraintArguments
    Person {
    }

    @ConstraintArguments
    boolean isOlderThan(int check) {
        return this.age() > check;
    }
}

Yavi generates one meta-class for each method which we can use to generate the validators as before.

Arguments2Validator<String, Integer, Person> validator = ArgumentsValidatorBuilder.of(Person::new)
  .builder(b -> b
    .constraint(_PersonArgumentsMeta.NAME, c -> c.notBlank())
    .constraint(_PersonArgumentsMeta.AGE, c -> c.positiveOrZero())
  )
  .build();

As before, we no longer need to manually specify the argument names or positions. We also no longer need to specify the correct type of constraint – our meta-class has already defined all of this for us.

8. Summary

This was a quick introduction to Yavi. There’s a lot more that can be done with this library, as well as offering good integration with popular frameworks such as Spring. Next time you need a validation library, why not give it a try?

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – LS – NPI (cat=Java)
announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

eBook Jackson – NPI EA – 3 (cat = Jackson)
3 Comments
Oldest
Newest
Inline Feedbacks
View all comments