Siva
Siva

Reputation: 1367

Using Jaxb2Marshaller to unmarshall an xml and validate against a schema

I am implementing a REST service with xml as the payload and have the following configuration to use Jaxb2Marshaller to unmarshall my xml. Here is the configuration from my spring context file

<bean id="jaxbMarshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
        <property name="classesToBeBound">
            <list>
                <value>com.my.examples.Product</value>
            </list>
        </property>
        <property name="schema" value="classpath:schemadefinitions/product.xsd" />
    </bean>

On my bean Product I have just this annotation as

@XmlRootElement(name="product") public class ProductInfo {

The issue is when I make the REST request it unmarshalls xml to bean properly but doesn't perform any validation against the schema configured with the marshaller. Am I missing anything ?

Upvotes: 1

Views: 6313

Answers (2)

Fritz Duchardt
Fritz Duchardt

Reputation: 11870

With Java 8 and JaxB 2.2.4, I don't see any problems with the original setup! Defining the schema property in the applicationcontext.xml is ALL you need to do in order to get schema validation going.

If one creates Jaxb2Marshaller "manually", one needs to make sure to call the afterPropertiesSet method after setting the schema resource, since it loads the schema resource into memory.

Upvotes: 1

Siva
Siva

Reputation: 1367

I had to attach a validationeventhandler to the marshaller as jaxb2Mashaller.setValidationEventHandler(...) Once this is set the unmarshaller started to validate input xml.

Upvotes: 1

Related Questions