javaspringjaxbxsdspring-oxm

Configure Spring 4.1 O/X mapping to validate inbound XML based on a schema?


Spring 4 O/X supports several XML unmarshallers behind its abstraction. We use JAXB2.

Can Spring validate the incoming XML against a schema? I didn't find anything in the official documentation nor in the spring-oxm schema that describe the configuration. This is my current configuration, pretty standard.

<bean id="jaxb2Marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
    <property name="marshallerProperties">
        <map>
            <!-- properties here -->
        </map>
    </property>
    <property name="classesToBeBound">
        <list>
            <value>com.example.Message1</value>
            <value>com.example.Message2</value>
        </list>
    </property>
</bean>

Solution

  • "Can Spring validate the incoming XML against a schema?"

    If you set the schema property:

    public class Jaxb2Marshaller ... {
        /**
         * Set the schema resource to use for validation.
         */
        public void setSchema(Resource schemaResource) {
            this.schemaResources = new Resource[] {schemaResource};
        }
    
        /**
         * Set the schema resources to use for validation.
         */
        public void setSchemas(Resource... schemaResources) {
            this.schemaResources = schemaResources;
        }
    }
    

    the Jaxb2Marshaller will use those schema(s) to validate. So in your context xml, you can just do something like

    <bean id="jaxb2Marshaller"
        class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
        <property name="schema" value="classpath:myschema.xsd"/> 
        <property name="classesToBeBound">
            <list>
                <value>com.example.Message1</value>
                <value>com.example.Message2</value>
            </list>
        </property>
    </bean>