Este contenido no está disponible en el idioma seleccionado.

Chapter 65. Bean Validation


Abstract

Bean validation is a Java standard that enables you to define runtime constraints by adding Java annotations to service classes or interfaces. Apache CXF uses interceptors to integrate this feature with Web service method invocations.

65.1. Introduction

Overview

Bean Validation 1.1 (JSR-349)—which is an evolution of the original Bean Validation 1.0 (JSR-303) standard—enables you to declare constraints that can be checked at run time, using Java annotations. You can use annotations to define constraints on the following parts of the Java code:

  • Fields in a bean class.
  • Method and constructor parameters.
  • Method return values.

Example of annotated class

The following example shows a Java class annotated with some standard bean validation constraints:

// Java
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Max;
import javax.validation.Valid;
...
public class Person {
    @NotNull private String firstName;
    @NotNull private String lastName;
    @Valid @NotNull private Person boss;

    public @NotNull String saveItem( @Valid @NotNull Person person, @Max( 23 ) BigDecimal age ) {
        // ...
    }
}

Bean validation or schema validation?

In some respects, bean validation and schema validation are quite similar. Configuring an endpoint with an XML schema is a well established way to validate messages at run time on a Web services endpoint. An XML schema can check many of the same constraints as bean validation on incoming and outgoing messages. Nevertheless, bean validation can sometimes be a useful alternative for one or more of the following reasons:

  • Bean validation enables you to define constraints independently of the XML schema (which is useful, for example, in the case of code-first service development).
  • If your current XML schema is too lax, you can use bean validation to define stricter constraints.
  • Bean validation lets you define custom constraints, which might be impossible to define using XML schema language.

Dependencies

The Bean Validation 1.1 (JSR-349) standard defines just the API, not the implementation. Dependencies must therefore be provided in two parts:

  • Core dependencies—provide the bean validation 1.1 API, Java unified expression language API and implementation.
  • Hibernate Validator dependencies—provides the implementation of bean validation 1.1.

Core dependencies

To use bean validation, you must add the following core dependencies to your project’s Maven pom.xml file:

<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>1.1.0.Final</version>
</dependency>
<dependency>
    <groupId>javax.el</groupId>
    <artifactId>javax.el-api</artifactId>
    <!-- use 3.0-b02 version for Java 6 -->
    <version>3.0.0</version>
</dependency>
<dependency>
    <groupId>org.glassfish</groupId>
    <artifactId>javax.el</artifactId>
    <!-- use 3.0-b01 version for Java 6 -->
    <version>3.0.0</version>
</dependency>
Note

The javax.el/javax.el-api and org.glassfish/javax.el dependencies provide the API and implementation of Java’s unified expression language. This expression language is used internally by bean validation, but is not important at the application programming level.

Hibernate Validator dependencies

To use the Hibernate Validator implementation of bean validation, you must add the following additional dependencies to your project’s Maven pom.xml file:

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>5.0.3.Final</version>
</dependency>

Resolving the validation provider in an OSGi environment

The default mechanism for resolving a validation provider involves scanning the classpath to find the provider resource. In the case of an OSGi (Apache Karaf) environment, however, this mechanism does not work, because the validation provider (for example, the Hibernate validator) is packaged in a separate bundle and is thus not automatically available in your application classpath. In the context of OSGi, the Hibernate validator needs to be wired to your application bundle, and OSGi needs a bit of help to do this successfully.

Configuring the validation provider explicitly in OSGi

In the context of OSGi, you need to configure the validation provider explicitly, instead of relying on automatic discovery. For example, if you are using the common validation feature (see the section called “Bean validation feature”) to enable bean validation, you must configure it with a validation provider, as follows:

<bean id="commonValidationFeature" class="org.apache.cxf.validation.BeanValidationFeature">
    <property name="provider" ref="beanValidationProvider"/>
</bean>

<bean id="beanValidationProvider" class="org.apache.cxf.validation.BeanValidationProvider">
    <constructor-arg ref="validationProviderResolver"/>
</bean>

<bean id="validationProviderResolver" class="org.example.HibernateValidationProviderResolver"/>

Where the HibernateValidationProviderResolver is a custom class that wraps the Hibernate validation provider.

Example HibernateValidationProviderResolver class

The following code example shows how to define a custom HibernateValidationProviderResolver, which resolves the Hibernate validator:

// Java
package org.example;

import static java.util.Collections.singletonList;
import org.hibernate.validator.HibernateValidator;
import javax.validation.ValidationProviderResolver;
import java.util.List;

/**
 * OSGi-friendly implementation of {@code javax.validation.ValidationProviderResolver} returning
 * {@code org.hibernate.validator.HibernateValidator} instance.
 *
 */
public class HibernateValidationProviderResolver implements ValidationProviderResolver {

    @Override
    public List getValidationProviders() {
        return singletonList(new HibernateValidator());
    }
}

When you build the preceding class in a Maven build system, which is configured to use the Maven bundle plug-in, your application will be wired to the Hibernate validator bundle at deploy time (assuming you have already deployed the Hibernate validator bundle to the OSGi container).

65.2. Developing Services with Bean Validation

65.2.1. Annotating a Service Bean

Overview

The first step in developing a service with bean validation is to apply the relevant validation annotations to the Java classes or interfaces that represent your services. The validation annotations enable you to apply constraints to method parameters, return values, and class fields, which are then checked at run time, every time the service is invoked.

Validating simple input parameters

To validate the parameters of a service method—where the parameters are simple Java types—you can apply any of the constraint annotations from the bean validation API (javax.validation.constraints package). For example, the following code example tests both parameters for nullness (@NotNull annotation), whether the id string matches the \\d+ regular expression (@Pattern annotation), and whether the length of the name string lies in the range 1 to 50:

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
...
@POST
@Path("/books")
public Response addBook(
        @NotNull @Pattern(regexp = "\\d+") @FormParam("id") String id,
        @NotNull @Size(min = 1, max = 50) @FormParam("name") String name) {
    // do some work
    return Response.created().build();
}

Validating complex input parameters

To validate complex input parameters (object instances), apply the @Valid annotation to the parameter, as shown in the following example:

import javax.validation.Valid;
...
@POST
@Path("/books")
public Response addBook( @Valid Book book ) {
    // do some work
    return Response.created().build();
}

The @Valid annotation does not specify any constraints by itself. When you annotate the Book parameter with @Valid, you are effectively telling the validation engine to look inside the definition of the Book class (recursively) to look for validation constraints. In this example, the Book class is defined with validation constraints on its id and name fields, as follows:

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
...
public class Book {
    @NotNull @Pattern(regexp = "\\d+") private String id;
    @NotNull @Size(min = 1, max = 50) private String name;

    // ...
}

Validating return values (non-Response)

To apply validation to regular method return values (non-Response), add the annotations in front of the method signature. For example, to test the return value for nullness (@NotNull annotation) and to test validation constraints recursively (@Valid annotation), annotate the getBook method as follows:

import javax.validation.constraints.NotNull;
import javax.validation.Valid;
...
@GET
@Path("/books/{bookId}")
@Override
@NotNull @Valid
public Book getBook(@PathParam("bookId") String id) {
    return new Book( id );
}

Validating return values (Response)

To apply validation to a method that returns a javax.ws.rs.core.Response object, you can use the same annotations as in the non-Response case. For example:

import javax.validation.constraints.NotNull;
import javax.validation.Valid;
import javax.ws.rs.core.Response;
...
@GET
@Path("/books/{bookId}")
@Valid @NotNull
public Response getBookResponse(@PathParam("bookId") String id) {
    return Response.ok( new Book( id ) ).build();
}

65.2.2. Standard Annotations

Bean validation constraints

Table 65.1, “Standard Annotations for Bean Validation” shows the standard annotations defined in the Bean Validation specification, which can be used to define constraints on fields and on method return values and parameters (none of the standard annotations can be applied at the class level).

Table 65.1. Standard Annotations for Bean Validation
AnnotationApplicable toDescription

@AssertFalse

Boolean, boolean

Checks that the annotated element is false.

@AssertTrue

Boolean, boolean

Checks that the annotated element is true.

@DecimalMax(value=, inclusive=)

BigDecimal, BigInteger, CharSequence, byte, short, int, long and primitive type wrappers

When inclusive=false, checks that the annotated value is less than the specified maximum. Otherwise, checks that the value is less than or equal to the specified maximum. The value parameter specifies the maximum in BigDecimal string format.

@DecimalMin(value=, inclusive=)

BigDecimal, BigInteger, CharSequence, byte, short, int, long and primitive type wrappers

When inclusive=false, checks that the annotated value is greater than the specified minimum. Otherwise, checks that the value is greater than or equal to the specified minimum. The value parameter specifies the minimum in BigDecimal string format.

@Digits(integer=, fraction=)

BigDecimal, BigInteger, CharSequence, byte, short, int, long and primitive type wrappers

Checks whether the annotated value is a number having up to integer digits and fraction fractional digits.

@Future

java.util.Date, java.util.Calendar

Checks whether the annotated date is in the future.

@Max(value=)

BigDecimal, BigInteger, CharSequence, byte, short, int, long and primitive type wrappers

Checks whether the annotated value is less than or equal to the specified maximum.

@Min(value=)

BigDecimal, BigInteger, CharSequence, byte, short, int, long and primitive type wrappers

Checks whether the annotated value is greater than or equal to the specified minimum.

@NotNull

Any type

Checks that the annotated value is not null.

@Null

Any type

Checks that the annotated value is null.

@Past

java.util.Date, java.util.Calendar

Checks whether the annotated date is in the past.

@Pattern(regex=, flag=)

CharSequence

Checks whether the annotated string matches the regular expression regex considering the given flag match.

@Size(min=, max=)

CharSequence, Collection, Map and arrays

Checks whether the size of the annotated collection, map, or array lies between min and max (inclusive).

@Valid

Any non-primitive type

Performs validation recursively on the annotated object. If the object is a collection or an array, the elements are validated recursively. If the object is a map, the value elements are validated recursively.

65.2.3. Custom Annotations

Defining custom constraints in Hibernate

It is possible to define your own custom constraints annotations with the bean validation API. For details of how to do this in the Hibernate validator implementation, see the Creating custom constraints chapter of the Hibernate Validator Reference Guide.

65.3. Configuring Bean Validation

65.3.1. JAX-WS Configuration

Overview

This section describes how to enable bean validation on a JAX-WS service endpoint, which is defined either in Blueprint XML or in Spring XML. The interceptors used to perform bean validation are common to both JAX-WS endpoints and JAX-RS 1.1 endpoints (JAX-RS 2.0 endpoints use different interceptor classes, however).

Namespaces

In the XML examples shown in this section, you must remember to map the jaxws namespace prefix to the appropriate namespace, either for Blueprint or Spring, as shown in the following table:

XML LanguageNamespace

Blueprint

http://cxf.apache.org/blueprint/jaxws

Spring

http://cxf.apache.org/jaxws

Bean validation feature

The simplest way to enable bean validation on a JAX-WS endpoint is to add the bean validation feature to the endpoint. The bean validation feature is implemented by the following class:

org.apache.cxf.validation.BeanValidationFeature
By adding an instance of this feature class to the JAX-WS endpoint (either through the Java API or through the jaxws:features child element of jaxws:endpoint in XML), you can enable bean validation on the endpoint. This feature installs two interceptors: an In interceptor that validates incoming message data; and an Out interceptor that validates return values (where the interceptors are created with default configuration parameters).

Sample JAX-WS configuration with bean validation feature

The following XML example shows how to enable bean validation functionality in a JAX-WS endpoint, by adding the commonValidationFeature bean to the endpoint as a JAX-WS feature:

<jaxws:endpoint xmlns:s="http://bookworld.com"
                serviceName="s:BookWorld"
                endpointName="s:BookWorldPort"
                implementor="#bookWorldValidation"
                address="/bwsoap">
    <jaxws:features>
        <ref bean="commonValidationFeature" />
    </jaxws:features>
</jaxws:endpoint>

<bean id="bookWorldValidation" class="org.apache.cxf.systest.jaxrs.validation.spring.BookWorldImpl"/>

<bean id="commonValidationFeature" class="org.apache.cxf.validation.BeanValidationFeature">
    <property name="provider" ref="beanValidationProvider"/>
</bean>

<bean id="beanValidationProvider" class="org.apache.cxf.validation.BeanValidationProvider">
    <constructor-arg ref="validationProviderResolver"/>
</bean>

<bean id="validationProviderResolver" class="org.example.HibernateValidationProviderResolver"/>

For a sample implementation of the HibernateValidationProviderResolver class, see the section called “Example HibernateValidationProviderResolver class”. It is only necessary to configure the beanValidationProvider in the context of an OSGi environment (Apache Karaf).

Note

Remember to map the jaxws prefix to the appropriate XML namespace for either Blueprint or Spring, depending on the context.

Common bean validation 1.1 interceptors

If you want to have more fine-grained control over the configuration of the bean validation, you can install the interceptors individually, instead of using the bean validation feature. In place of the bean validation feature, you can configure one or both of the following interceptors:

org.apache.cxf.validation.BeanValidationInInterceptor
When installed in a JAX-WS (or JAX-RS 1.1) endpoint, validates resource method parameters against validation constraints. If validation fails, raises the javax.validation.ConstraintViolationException exception. To install this interceptor, add it to the endpoint through the jaxws:inInterceptors child element in XML (or the jaxrs:inInterceptors child element in XML).
org.apache.cxf.validation.BeanValidationOutInterceptor
When installed in a JAX-WS (or JAX-RS 1.1) endpoint, validates response values against validation constraints. If validation fails, raises the javax.validation.ConstraintViolationException exception. To install this interceptor, add it to the endpoint through the jaxws:outInterceptors child element in XML (or the jaxrs:outInterceptors child element in XML).

Sample JAX-WS configuration with bean validation interceptors

The following XML example shows how to enable bean validation functionality in a JAX-WS endpoint, by explicitly adding the relevant In interceptor bean and Out interceptor bean to the endpoint:

<jaxws:endpoint xmlns:s="http://bookworld.com"
                serviceName="s:BookWorld"
                endpointName="s:BookWorldPort"
                implementor="#bookWorldValidation"
                address="/bwsoap">
    <jaxws:inInterceptors>
        <ref bean="validationInInterceptor" />
    </jaxws:inInterceptors>

    <jaxws:outInterceptors>
        <ref bean="validationOutInterceptor" />
    </jaxws:outInterceptors>
</jaxws:endpoint>

<bean id="bookWorldValidation" class="org.apache.cxf.systest.jaxrs.validation.spring.BookWorldImpl"/>

<bean id="validationInInterceptor" class="org.apache.cxf.validation.BeanValidationInInterceptor">
    <property name="provider" ref="beanValidationProvider"/>
</bean>
<bean id="validationOutInterceptor" class="org.apache.cxf.validation.BeanValidationOutInterceptor">
    <property name="provider" ref="beanValidationProvider"/>
</bean>

<bean id="beanValidationProvider" class="org.apache.cxf.validation.BeanValidationProvider">
    <constructor-arg ref="validationProviderResolver"/>
</bean>

<bean id="validationProviderResolver" class="org.example.HibernateValidationProviderResolver"/>

For a sample implementation of the HibernateValidationProviderResolver class, see the section called “Example HibernateValidationProviderResolver class”. It is only necessary to configure the beanValidationProvider in the context of an OSGi environment (Apache Karaf).

Configuring a BeanValidationProvider

The org.apache.cxf.validation.BeanValidationProvider is a simple wrapper class that wraps the bean validation implementation (validation provider). By overriding the default BeanValidationProvider class, you can customize the implementation of bean validation. The BeanValidationProvider bean enables you to override one or more of the following provider classes:

javax.validation.ParameterNameProvider
Provides names for method and constructor parameters. Note that this class is needed, because the Java reflection API does not give you access to the names of method parameters or constructor parameters.
javax.validation.spi.ValidationProvider<T>
Provides an implementation of bean validation for the specified type, T. By implementing your own ValidationProvider class, you can define custom validation rules for your own classes. This mechanism effectively enables you to extend the bean validation framework.
javax.validation.ValidationProviderResolver
Implements a mechanism for discovering ValidationProvider classes and returns a list of the discovered classes. The default resolver looks for a META-INF/services/javax.validation.spi.ValidationProvider file on the classpath, which should contain a list of ValidationProvider classes.
javax.validation.ValidatorFactory
A factory that returns javax.validation.Validator instances.
org.apache.cxf.validation.ValidationConfiguration
A CXF wrapper class that enables you override more classes from the validation provider layer.

To customize the BeanValidationProvider, pass a custom BeanValidationProvider instance to the constructor of the validation In interceptor and to the constructor of the validation Out interceptor. For example:

<bean id="validationProvider" class="org.apache.cxf.validation.BeanValidationProvider" />

<bean id="validationInInterceptor" class="org.apache.cxf.validation.BeanValidationInInterceptor">
    <property name="provider" ref="validationProvider" />
</bean>

<bean id="validationOutInterceptor" class="org.apache.cxf.validation.BeanValidationOutInterceptor">
    <property name="provider" ref="validationProvider" />
</bean>

65.3.2. JAX-RS Configuration

Overview

This section describes how to enable bean validation on a JAX-RS service endpoint, which is defined either in Blueprint XML or in Spring XML. The interceptors used to perform bean validation are common to both JAX-WS endpoints and JAX-RS 1.1 endpoints (JAX-RS 2.0 endpoints use different interceptor classes, however).

Namespaces

In the XML examples shown in this section, you must remember to map the jaxws namespace prefix to the appropriate namespace, either for Blueprint or Spring, as shown in the following table:

XML LanguageNamespace

Blueprint

http://cxf.apache.org/blueprint/jaxws

Spring

http://cxf.apache.org/jaxws

Bean validation feature

The simplest way to enable bean validation on a JAX-RS endpoint is to add the bean validation feature to the endpoint. The bean validation feature is implemented by the following class:

org.apache.cxf.validation.BeanValidationFeature
By adding an instance of this feature class to the JAX-RS endpoint (either through the Java API or through the jaxrs:features child element of jaxrs:server in XML), you can enable bean validation on the endpoint. This feature installs two interceptors: an In interceptor that validates incoming message data; and an Out interceptor that validates return values (where the interceptors are created with default configuration parameters).

Validation exception mapper

A JAX-RS endpoint also requires you to configure a validation exception mapper, which is responsible for mapping validation exceptions to HTTP error responses. The following class implements validation exception mapping for JAX-RS:

org.apache.cxf.jaxrs.validation.ValidationExceptionMapper
Implements validation exception mapping in accordance with the JAX-RS 2.0 specification: any input parameter validation violations are mapped to HTTP status code 400 Bad Request; and any return value validation violation (or internal validation violation) is mapped to HTTP status code 500 Internal Server Error.

Sample JAX-RS configuration

The following XML example shows how to enable bean validation functionality in a JAX-RS endpoint, by adding the commonValidationFeature bean as a JAX-RS feature and by adding the exceptionMapper bean as a JAX-RS provider:

<jaxrs:server address="/bwrest">
    <jaxrs:serviceBeans>
        <ref bean="bookWorldValidation"/>
    </jaxrs:serviceBeans>
    <jaxrs:providers>
        <ref bean="exceptionMapper"/>
    </jaxrs:providers>
    <jaxrs:features>
        <ref bean="commonValidationFeature" />
    </jaxrs:features>
</jaxrs:server>

<bean id="bookWorldValidation" class="org.apache.cxf.systest.jaxrs.validation.spring.BookWorldImpl"/>
<beanid="exceptionMapper"class="org.apache.cxf.jaxrs.validation.ValidationExceptionMapper"/>

<bean id="commonValidationFeature" class="org.apache.cxf.validation.BeanValidationFeature">
    <property name="provider" ref="beanValidationProvider"/>
</bean>

<bean id="beanValidationProvider" class="org.apache.cxf.validation.BeanValidationProvider">
    <constructor-arg ref="validationProviderResolver"/>
</bean>

<bean id="validationProviderResolver" class="org.example.HibernateValidationProviderResolver"/>

For a sample implementation of the HibernateValidationProviderResolver class, see the section called “Example HibernateValidationProviderResolver class”. It is only necessary to configure the beanValidationProvider in the context of an OSGi environment (Apache Karaf).

Note

Remember to map the jaxrs prefix to the appropriate XML namespace for either Blueprint or Spring, depending on the context.

Common bean validation 1.1 interceptors

Instead of using the bean validation feature, you can optionally install bean validation interceptors to get more fine-grained control over the validation implementation. JAX-RS uses the same interceptors as JAX-WS for this purpose—see the section called “Common bean validation 1.1 interceptors”

Sample JAX-RS configuration with bean validation interceptors

The following XML example shows how to enable bean validation functionality in a JAX-RS endpoint, by explicitly adding the relevant In interceptor bean and Out interceptor bean to the server endpoint:

<jaxrs:server address="/">
    <jaxrs:inInterceptors>
        <ref bean="validationInInterceptor" />
    </jaxrs:inInterceptors>

    <jaxrs:outInterceptors>
        <ref bean="validationOutInterceptor" />
    </jaxrs:outInterceptors>

    <jaxrs:serviceBeans>
    ...
    </jaxrs:serviceBeans>

    <jaxrs:providers>
        <ref bean="exceptionMapper"/>
    </jaxrs:providers>
</jaxrs:server>

<bean id="exceptionMapper" class="org.apache.cxf.jaxrs.validation.ValidationExceptionMapper"/>

<bean id="validationInInterceptor" class="org.apache.cxf.validation.BeanValidationInInterceptor">
    <property name="provider" ref="beanValidationProvider" />
</bean>

<bean id="validationOutInterceptor" class="org.apache.cxf.validation.BeanValidationOutInterceptor">
    <property name="provider" ref="beanValidationProvider" />
</bean>

<bean id="beanValidationProvider" class="org.apache.cxf.validation.BeanValidationProvider">
    <constructor-arg ref="validationProviderResolver"/>
</bean>

<bean id="validationProviderResolver" class="org.example.HibernateValidationProviderResolver"/>

For a sample implementation of the HibernateValidationProviderResolver class, see the section called “Example HibernateValidationProviderResolver class”. It is only necessary to configure the beanValidationProvider in the context of an OSGi environment (Apache Karaf).

Configuring a BeanValidationProvider

You can inject a custom BeanValidationProvider instance into the validation interceptors, as described in the section called “Configuring a BeanValidationProvider”.

65.3.3. JAX-RS 2.0 Configuration

Overview

Unlike JAX-RS 1.1 (which shares common validation interceptors with JAX-WS), the JAX-RS 2.0 configuration relies on dedicated validation interceptor classes that are specific to JAX-RS 2.0.

Bean validation feature

For JAX-RS 2.0, there is a dedicated bean validation feature, which is implemented by the following class:

org.apache.cxf.validation.JAXRSBeanValidationFeature
By adding an instance of this feature class to the JAX-RS endpoint (either through the Java API or through the jaxrs:features child element of jaxrs:server in XML), you can enable bean validation on a JAX-RS 2.0 server endpoint. This feature installs two interceptors: an In interceptor that validates incoming message data; and an Out interceptor that validates return values (where the interceptors are created with default configuration parameters).

Validation exception mapper

JAX-RS 2.0 uses the same validation exception mapper class as JAX-RS 1.x:

org.apache.cxf.jaxrs.validation.ValidationExceptionMapper
Implements validation exception mapping in accordance with the JAX-RS 2.0 specification: any input parameter validation violations are mapped to HTTP status code 400 Bad Request; and any return value validation violation (or internal validation violation) is mapped to HTTP status code 500 Internal Server Error.

Bean validation invoker

If you configure the JAX-RS service with a non-default lifecycle policy (for example, using Spring lifecycle management), you should also register a org.apache.cxf.jaxrs.validation.JAXRSBeanValidationInvoker instance—using the jaxrs:invoker element in the endpoint configuration—with the service endpoint, to ensure that bean validation is invoked correctly.

For more details about JAX-RS service lifecycle management, see the section called “Lifecycle management in Spring XML”.

Sample JAX-RS 2.0 configuration with bean validation feature

The following XML example shows how to enable bean validation functionality in a JAX-RS 2.0 endpoint, by adding the jaxrsValidationFeature bean as a JAX-RS feature and by adding the exceptionMapper bean as a JAX-RS provider:

<jaxrs:server address="/">
    <jaxrs:serviceBeans>
    ...
    </jaxrs:serviceBeans>
    <jaxrs:providers>
        <ref bean="exceptionMapper"/>
    </jaxrs:providers>
    <jaxrs:features>
        <ref bean="jaxrsValidationFeature" />
    </jaxrs:features>
</jaxrs:server>

<bean id="exceptionMapper" class="org.apache.cxf.jaxrs.validation.ValidationExceptionMapper"/>
<bean id="jaxrsValidationFeature" class="org.apache.cxf.validation.JAXRSBeanValidationFeature">
    <property name="provider" ref="beanValidationProvider"/>
</bean>

<bean id="beanValidationProvider" class="org.apache.cxf.validation.BeanValidationProvider">
    <constructor-arg ref="validationProviderResolver"/>
</bean>

<bean id="validationProviderResolver" class="org.example.HibernateValidationProviderResolver"/>

For a sample implementation of the HibernateValidationProviderResolver class, see the section called “Example HibernateValidationProviderResolver class”. It is only necessary to configure the beanValidationProvider in the context of an OSGi environment (Apache Karaf).

Note

Remember to map the jaxrs prefix to the appropriate XML namespace for either Blueprint or Spring, depending on the context.

Common bean validation 1.1 interceptors

If you want to have more fine-grained control over the configuration of the bean validation, you can install the JAX-RS interceptors individually, instead of using the bean validation feature. Configure one or both of the following JAX-RS interceptors:

org.apache.cxf.validation.JAXRSBeanValidationInInterceptor
When installed in a JAX-RS 2.0 server endpoint, validates resource method parameters against validation constraints. If validation fails, raises the javax.validation.ConstraintViolationException exception. To install this interceptor, add it to the endpoint through the jaxrs:inInterceptors child element in XML.
org.apache.cxf.validation.JAXRSBeanValidationOutInterceptor
When installed in a JAX-RS 2.0 endpoint, validates response values against validation constraints. If validation fails, raises the javax.validation.ConstraintViolationException exception. To install this interceptor, add it to the endpoint through the jaxrs:inInterceptors child element in XML.

Sample JAX-RS 2.0 configuration with bean validation interceptors

The following XML example shows how to enable bean validation functionality in a JAX-RS 2.0 endpoint, by explicitly adding the relevant In interceptor bean and Out interceptor bean to the server endpoint:

<jaxrs:server address="/">
    <jaxrs:inInterceptors>
        <ref bean="validationInInterceptor" />
    </jaxrs:inInterceptors>

    <jaxrs:outInterceptors>
        <ref bean="validationOutInterceptor" />
    </jaxrs:outInterceptors>

    <jaxrs:serviceBeans>
    ...
    </jaxrs:serviceBeans>

    <jaxrs:providers>
        <ref bean="exceptionMapper"/>
    </jaxrs:providers>
</jaxrs:server>

<bean id="exceptionMapper" class="org.apache.cxf.jaxrs.validation.ValidationExceptionMapper"/>

<bean id="validationInInterceptor" class="org.apache.cxf.jaxrs.validation.JAXRSBeanValidationInInterceptor">
    <property name="provider" ref="beanValidationProvider" />
</bean>

<bean id="validationOutInterceptor" class="org.apache.cxf.jaxrs.validation.JAXRSBeanValidationOutInterceptor">
    <property name="provider" ref="beanValidationProvider" />
</bean>

<bean id="beanValidationProvider" class="org.apache.cxf.validation.BeanValidationProvider">
    <constructor-arg ref="validationProviderResolver"/>
</bean>

<bean id="validationProviderResolver" class="org.example.HibernateValidationProviderResolver"/>

For a sample implementation of the HibernateValidationProviderResolver class, see the section called “Example HibernateValidationProviderResolver class”. It is only necessary to configure the beanValidationProvider in the context of an OSGi environment (Apache Karaf).

Configuring a BeanValidationProvider

You can inject a custom BeanValidationProvider instance into the validation interceptors, as described in the section called “Configuring a BeanValidationProvider”.

Configuring a JAXRSParameterNameProvider

The org.apache.cxf.jaxrs.validation.JAXRSParameterNameProvider class is an implementation of the javax.validation.ParameterNameProvider interface, which can be used to provide the names for method and constructor parameters in the context of JAX-RS 2.0 endpoints.

Red Hat logoGithubRedditYoutubeTwitter

Aprender

Pruebe, compre y venda

Comunidades

Acerca de la documentación de Red Hat

Ayudamos a los usuarios de Red Hat a innovar y alcanzar sus objetivos con nuestros productos y servicios con contenido en el que pueden confiar.

Hacer que el código abierto sea más inclusivo

Red Hat se compromete a reemplazar el lenguaje problemático en nuestro código, documentación y propiedades web. Para más detalles, consulte el Blog de Red Hat.

Acerca de Red Hat

Ofrecemos soluciones reforzadas que facilitan a las empresas trabajar en plataformas y entornos, desde el centro de datos central hasta el perímetro de la red.

© 2024 Red Hat, Inc.