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

Enterprise Java development depends heavily on Spring. It’s a powerful framework that simplifies the process of building strong, scalable apps. We can use Spring to build REST APIs, microservices, or full-stack web apps efficiently and cleanly.

However, as apps become larger, they require clear and understandable validation. Custom validation messages solve this problem. Developers can use them to give users useful feedback instead of confusing error messages.

In this tutorial, we’ll discuss Spring Boot’s validation message system, how to configure it effectively, streamline error handling, and make message management more intuitive.

2. Binding Custom Validation Messages

To guide users and guarantee data integrity, validation is crucial. Spring Boot uses the Java Bean Validation framework (JSR-380), enabling developers to annotate fields with constraints such as @NotBlank, @Email, and @Min.

However, for improved localization and maintainability, we can bind error messages to external properties rather than hard-coding them.

2.1. Add Validation Dependency

To use validation annotations in our Spring Boot application, we need to include the Spring Boot Starter Validation dependency. This starter wraps Hibernate Validator, which is the reference implementation of the Bean Validation API (JSR-380).

For Maven Configuration, we’ll add the following to our pom.xml:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

Once added, Spring Boot will automatically add the necessary components to support validation across our application, including REST controllers, service layers, and form inputs.

2.2. Annotate DTO with Message Keys

After setting up the validation dependency, let’s add annotations to our Data Transfer Objects (DTOs) to impose rules on incoming data.

Depending on our configuration, these annotations are included in either the jakarta.validation.constraints or javax.validation.constraints package.

Let’s use constraint annotations and reference message keys:

public class UserDTO {
    @NotBlank(message = "{user.name.notblank}")
    private String name;
    @Email(message = "{user.email.invalid}")
    private String email;
    @Min(value = 18, message = "{user.age.min}")
    private int age;
    // Getters and setters
}

@NotBlank verifies that the name field is not empty or null. @Email verifies the email field’s format, and @Min verifies that the person is at least eighteen years old.

We’ll use message keys such as user.name.notblank to convey error messages rather than hard-coding them directly into the annotation (e.g., message = “Name must not be blank”).

In the next step, we’ll use these keys from a properties file (ValidationMessages.properties).

2.3. Create and Structure Validation Messages

Let’s now create validation messages. The core of Spring Boot’s custom validation messaging is the ValidationMessages.properties file. It allows for cleaner logic, simpler maintenance, and localization support by externalizing error messages from our code.

We’ll need to place the file in our project’s directory path:

our-project/
└── src/
└── main/
└── resources/
└── ValidationMessages.properties

Spring Boot automatically detects this file if named correctly and placed in the classpath.

Every entry in the file associates a human-readable message with a message key that we’ll use in our DTO annotations, as shown example below:

# ValidationMessages.properties
user.name.notblank=Name must not be blank.
user.email.invalid=Please provide a valid email address.
user.age.min=Age must be at least 18.

These keys correspond to the message attributes in DTO:

@NotBlank(message = "{user.name.notblank}")
@Email(message = "{user.email.invalid}")
@Min(value = 18, message = "{user.age.min}")

3. Optional Message Source Configuration

By default, Spring Boot loads validation messages from ValidationMessages.properties on the classpath.

For example, if we want to support multiple languages, change the encoding, or use a different filename, we can explicitly configure a MessageSource bean. The following steps are optional, but highly recommended:

  • Internationalization (I18n) – Supporting multiple locales
  • Custom file naming – Using messages.properties or other names
  • Advanced control – Configuring fallback behavior, encoding, etc.

3.1. What Is a Message Source?

This Spring interface retrieves messages using keys and locales in .properties files. It is the main component of Spring’s i18n and validation messaging system.

To configure a MessageSource, we’ll add the following bean to our Spring Boot application class or a configuration class:

@Bean
public MessageSource messageSource() {
    ResourceBundleMessageSource source = new ResourceBundleMessageSource();
    source.setBasename("ValidationMessages");     // Name of your properties file (without .properties)
    source.setDefaultEncoding("UTF-8");           // Ensures proper character encoding
    source.setUseCodeAsDefaultMessage(true);      // Optional: fallback to key if message not found
    return source;
}

Here are the key properties and purpose:

Property Purpose
setBasename(“…”) Specifies the base name of the message file (e.g., ValidationMessages)
setDefaultEncoding(“UTF-8”) Ensures proper rendering of special characters and non-English text
setUseCodeAsDefaultMessage() Falls back to the key if no message is found (useful for debugging)

3.2. Supporting Multiple Languages

To support international users, we’ll create locale-specific files:

src/main/resources/
├── ValidationMessages_en.properties
├── ValidationMessages_fr.properties
├── ValidationMessages_ar.properties

Spring automatically resolves the appropriate file based on the user’s locale, which can be configured using browser preferences, HTTP headers, and configuration.

For example, ValidationMessages_fr.properties for French Localization.

4. Validate in Controller

The next step is to initiate validation and gracefully handle errors in our controller after we have annotated our DTO with validation constraints and bound custom messages.

Using the @Valid annotation and BindingResult interface, Spring Boot makes this easy. Let’s discuss a REST controller method that accepts a UserDTO object and validates it:

@PostMapping("/register")
public ResponseEntity<?> registerUser(@Valid @RequestBody UserDTO userDTO, BindingResult result) {
    if (result.hasErrors()) {
        List<String> errors = result.getFieldErrors()
          .stream()
          .map(FieldError::getDefaultMessage)
          .collect(Collectors.toList());
        return ResponseEntity.badRequest().body(errors);
    }
    // Proceed with registration logic
    return ResponseEntity.ok("User registered successfully");
}

The following table elaborates on the role of each component of the above code:

Component Role
@Valid Triggers validation on the incoming UserDTO object
BindingResult Captures validation errors (if any)
FieldError Represents a single field-level error
getDefaultMessage() Retrieves the custom message from ValidationMessages.properties

4.1. Why Use Binding Result?

Spring will throw an error if we don’t use BindingResult. Though it works, this is not the best option for changing error formats, multiple error aggregation, or generating structured JSON responses.

We are in complete control of how validation errors are handled and displayed when we use BindingResult.

Let’s take an example of a JSON Error Response when a user provides inaccurate data. The controller may return:

[
"Name must not be blank.",
"Please provide a valid email address.",
"Age must be at least 18."
]

This is clean, readable, and directly tied to the custom messages.

5. Conclusion

In this article, we discussed how binding custom validation messages in Spring Boot simplifies user feedback. This is done by externalizing error messages into properties files.

Further, we elaborated on how a clean, maintainable, and user-friendly validation flow can be created in a few simple steps. This includes adding validation dependencies, annotating DTOs, configuring message sources, and handling errors in controllers. 

This method further facilitates localization and scalable application design in addition to increasing clarity. 

The tested code is available over on GitHub.

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.

eBook Jackson – NPI EA – 3 (cat = Jackson)