Easily configure validators via properties in a Spring Boot project

The annotations from the Java Validation API provide a convenient and flexible tool to ensure the quality of an application’s input. Some of them have parameters that allow for the validation’s fine tuning. The main drawback is that the parameters’ values are resolved at compile time, that’s why they must be static final constants. We’ll show how we can overcome this limitation and configure validators via properties in a Spring Boot project. It would be […]

File download from a REST API with Spring Boot

When calling a REST endpoint the response is generally returned as JSON. What if we want to give the user the chance to download the same data as a file? We can build an endpoint that returns data as a downloadable file. The following example shows how easy it is to create an endpoint to download a file with Spring. The project We’ll build a Spring Boot project with spring-boot-starter-web as the only required dependency, […]

How to mock custom validators when unit testing

In the previous post we saw how dependencies in custom constraint validators can be mocked when we want to unit test our validation layer in a Spring Boot application. It all boils down to the creation of a custom ValidatorFactory that can use our custom ConstraintValidators, those will have their dependencies mocked and manually injected. But what if we want to mock an entire ConstraintValidator rather than just its dependencies? There are some situations where […]

How to mock dependencies when unit testing custom validators

The Java Validation API provides a very convenient API for input validation. It is part of the JavaEE spec, nevertheless it can be used within a Spring application too. Addressing the whole functioning of the Java Validation API is beyond the scope of this post, we will focus instead on how to unit test the validation layer. In this regard, we will show how to mock dependencies that might be injected in your custom constraint […]

Decorator pattern in a Spring Boot project

Anyone who has worked with Hibernate has already faced the LazyInitializationException. It occurs when trying to access an association that hasn’t been fetched along with an entity. To avoid this, the required association(s) must be fetched within the same database transaction. Fetching several to-one associations can be achieved in one single JPQL query via several JOIN FETCH clauses or by defining an appropriate EntityGraph. For to-many associations neither of those two approaches is possible: Hibernate […]