Java web bean validation

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.

Источник

Знакомство с Bean Validation API

Не так давно в Яве не существовало стандарта, описывающего способ валидации данных. Каждый выкручивался как мог, писались (и пишутся) свои поделки а так же используются некоторые возможности широко распространенных сервисов как Spring или Hibernate. Наибольшей проблемой было то, что валидация могла быть реализована отдельно от предметной модели и быть редунданто расбросанной по фронт- и бэкэнду. Теперь, при помощи стандарта JSR 303: Bean Validation (практически это явлается стандартизированным валидатором Hibernate) становится возможным следовать принципу «Don’t Repeat Yourself»: объявлять ограничения для данных прямо в предметной модели и валидировать данные где угодно, хоть на сервере, хоть в десктопном приложении.

Пример использования

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;

@NotNull(message= «Имя должно быть задано» )
String firstname;

@NotNull(message= «Фамилия должна быть задана» )
@Size(min = 3, message= «Длина фамилии должна быть больше трех» )
String lastname;

@Override
public String toString() return String .format( «firstname: [%s], lastname: [%s], email: [%s]» ,
firstname, lastname, email);
>

public static void validate(Object object , Validator validator) Set> constraintViolations = validator
.validate( object );

System. out .println( object );
System. out .println( String .format( «Кол-во ошибок: %d» ,
constraintViolations.size()));

for (ConstraintViolation cv : constraintViolations)
System. out .println( String .format(
«Внимание, ошибка! property: [%s], value: [%s], message: [%s]» ,
cv.getPropertyPath(), cv.getInvalidValue(), cv.getMessage()));
>

public static void main( String [] args) ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
Validator validator = vf.getValidator();

User user = new User();
validate(user, validator);

user.firstname = «Вася» ;
validate(user, validator);

user.lastname = «Пу» ;
validate(user, validator);

user.lastname = «Пупкин» ;
validate(user, validator);

user.email = «вася пупкин@example.com» ;
validate(user, validator);

user.email = «vasya.poupkine@example.com» ;
validate(user, validator);

>

* This source code was highlighted with Source Code Highlighter .

  • Объявление «ограничений» (constraints) на данные в модели при помощи аннотаций
  • Получение валидатора через фэктори
  • валидация объектов и обработка сообщений о нарушениях объявленных рамок (ConstraintViolations)

На этом закончим знакомство с JSR 303. А с такими подробностями как расширение/написание собственных ограничений, интернализации сообщений, конфигурации фэктори и прочим можно ознакомится и в самом стандарте

P.S. Для запуска кода в примере использовалась имплементация Hibernate 4.0.0 Beta2, приятных экспериментов!

Источник

Оцените статью