Java Bean Validation
The Spring Framework provides support for the Java Bean Validation API.
Overview of Bean Validation
Bean Validation provides a common way of validation through constraint declaration and metadata for Java applications. To use it, you annotate domain model properties with declarative validation constraints which are then enforced by the runtime. There are built-in constraints, and you can also define your own custom constraints.
Consider the following example, which shows a simple PersonForm model with two properties:
class PersonForm( private val name: String, private val age: Int )
Bean Validation lets you declare constraints as the following example shows:
class PersonForm( @get:NotNull @get:Size(max=64) private val name: String, @get:Min(0) private val age: Int )
A Bean Validation validator then validates instances of this class based on the declared constraints. See Bean Validation for general information about the API. See the Hibernate Validator documentation for specific constraints. To learn how to set up a bean validation provider as a Spring bean, keep reading.
Configuring a Bean Validation Provider
Spring provides full support for the Bean Validation API including the bootstrapping of a Bean Validation provider as a Spring bean. This lets you inject a jakarta.validation.ValidatorFactory or jakarta.validation.Validator wherever validation is needed in your application.
You can use the LocalValidatorFactoryBean to configure a default Validator as a Spring bean, as the following example shows:
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean; @Configuration public class AppConfig < @Bean public LocalValidatorFactoryBean validator() < return new LocalValidatorFactoryBean(); >>
The basic configuration in the preceding example triggers bean validation to initialize by using its default bootstrap mechanism. A Bean Validation provider, such as the Hibernate Validator, is expected to be present in the classpath and is automatically detected.
Injecting a Validator
LocalValidatorFactoryBean implements both jakarta.validation.ValidatorFactory and jakarta.validation.Validator , as well as Spring’s org.springframework.validation.Validator . You can inject a reference to either of these interfaces into beans that need to invoke validation logic.
You can inject a reference to jakarta.validation.Validator if you prefer to work with the Bean Validation API directly, as the following example shows:
import jakarta.validation.Validator; @Service public class MyService
import jakarta.validation.Validator; @Service class MyService(@Autowired private val validator: Validator)
You can inject a reference to org.springframework.validation.Validator if your bean requires the Spring Validation API, as the following example shows:
import org.springframework.validation.Validator; @Service public class MyService
import org.springframework.validation.Validator @Service class MyService(@Autowired private val validator: Validator)
Configuring Custom Constraints
Each bean validation constraint consists of two parts:
- A @Constraint annotation that declares the constraint and its configurable properties.
- An implementation of the jakarta.validation.ConstraintValidator interface that implements the constraint’s behavior.
To associate a declaration with an implementation, each @Constraint annotation references a corresponding ConstraintValidator implementation class. At runtime, a ConstraintValidatorFactory instantiates the referenced implementation when the constraint annotation is encountered in your domain model.
By default, the LocalValidatorFactoryBean configures a SpringConstraintValidatorFactory that uses Spring to create ConstraintValidator instances. This lets your custom ConstraintValidators benefit from dependency injection like any other Spring bean.
The following example shows a custom @Constraint declaration followed by an associated ConstraintValidator implementation that uses Spring for dependency injection:
@Target() @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy=MyConstraintValidator.class) public @interface MyConstraint
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.FIELD) @Retention(AnnotationRetention.RUNTIME) @Constraint(validatedBy = MyConstraintValidator::class) annotation class MyConstraint
import jakarta.validation.ConstraintValidator; public class MyConstraintValidator implements ConstraintValidator < @Autowired; private Foo aDependency; // . >
import jakarta.validation.ConstraintValidator class MyConstraintValidator(private val aDependency: Foo) : ConstraintValidator < // . >
As the preceding example shows, a ConstraintValidator implementation can have its dependencies @Autowired as any other Spring bean.
Spring-driven Method Validation
You can integrate the method validation feature supported by Bean Validation 1.1 (and, as a custom extension, also by Hibernate Validator 4.3) into a Spring context through a MethodValidationPostProcessor bean definition:
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor; @Configuration public class AppConfig < @Bean public MethodValidationPostProcessor validationPostProcessor() < return new MethodValidationPostProcessor(); >>
To be eligible for Spring-driven method validation, all target classes need to be annotated with Spring’s @Validated annotation, which can optionally also declare the validation groups to use. See MethodValidationPostProcessor for setup details with the Hibernate Validator and Bean Validation 1.1 providers.
Method validation relies on AOP Proxies around the target classes, either JDK dynamic proxies for methods on interfaces or CGLIB proxies. There are certain limitations with the use of proxies, some of which are described in Understanding AOP Proxies. In addition remember to always use methods and accessors on proxied classes; direct field access will not work.
Additional Configuration Options
The default LocalValidatorFactoryBean configuration suffices for most cases. There are a number of configuration options for various Bean Validation constructs, from message interpolation to traversal resolution. See the LocalValidatorFactoryBean javadoc for more information on these options.
Configuring a DataBinder
You can configure a DataBinder instance with a Validator . Once configured, you can invoke the Validator by calling binder.validate() . Any validation Errors are automatically added to the binder’s BindingResult .
The following example shows how to use a DataBinder programmatically to invoke validation logic after binding to a target object:
Foo target = new Foo(); DataBinder binder = new DataBinder(target); binder.setValidator(new FooValidator()); // bind to the target object binder.bind(propertyValues); // validate the target object binder.validate(); // get BindingResult that includes any validation errors BindingResult results = binder.getBindingResult();
val target = Foo() val binder = DataBinder(target) binder.validator = FooValidator() // bind to the target object binder.bind(propertyValues) // validate the target object binder.validate() // get BindingResult that includes any validation errors val results = binder.bindingResult
You can also configure a DataBinder with multiple Validator instances through dataBinder.addValidators and dataBinder.replaceValidators . This is useful when combining globally configured bean validation with a Spring Validator configured locally on a DataBinder instance. See Spring MVC Validation Configuration.
Spring MVC 3 Validation
See Validation in the Spring MVC chapter.
Apache®, Apache Tomcat®, Apache Kafka®, Apache Cassandra™, and Apache Geode™ are trademarks or registered trademarks of the Apache Software Foundation in the United States and/or other countries. Java™, Java™ SE, Java™ EE, and OpenJDK™ are trademarks of Oracle and/or its affiliates. Kubernetes® is a registered trademark of the Linux Foundation in the United States and other countries. Linux® is the registered trademark of Linus Torvalds in the United States and other countries. Windows® and Microsoft® Azure are registered trademarks of Microsoft Corporation. “AWS” and “Amazon Web Services” are trademarks or registered trademarks of Amazon.com Inc. or its affiliates. All other trademarks and copyrights are property of their respective owners and are only mentioned for informative purposes. Other names may be trademarks of their respective owners.
Spring Validation Message Interpolation
Repeatedly, code that works in dev breaks down in production. Java performance issues are difficult to track down or predict.
Simply put, Digma provides immediate code feedback. As an IDE plugin, it identifies issues with your code as it is currently running in test and prod.
The feedback is available from the minute you are writing it.
Imagine being alerted to any regression or code smell as you’re running and debugging locally. Also, identifying weak spots that need attending to, based on integration testing results.
Of course, Digma is free for developers.
As always, the writeup is super practical and based on a simple application that can work with documents with a mix of encrypted and unencrypted fields.
We rely on other people’s code in our own work. Every day.
It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.
The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.
Lightrun is a new kind of debugger.
It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.
Learn more in this quick, 5-minute Lightrun tutorial:
Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.
The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.
Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.
Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:
DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.
The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.
And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.