Embed XML configuration directly in Spring application context
I have a Java object which is able to configure itself given an XML configuration description (it takes other descriptions as well, but I'm interested in the XML at the moment). I'm wondering if I can embed the XML description directly into a Spring application context description. I'm imagining something like:
<bean id="myXMLConfiguredBean" class="com.example.Foo"> <constructor-arg type="xml"> <myconfig xmlns="http://example.com/foo/config"> <bar>42</bar> </myconfig> </constructor-arg> </bean>
but I have no idea if that - or something like it - is possible. I realise I could embed myconfig in a CDATA section, but that seems a bit ugly.
Spring's XSD allows <constructor-arg> to contain any XML through:
<xsd:element name="constructor-arg"> <xsd:complexType> <xsd:sequence> <xsd:element ref="description" minOccurs="0" /> <xsd:choice minOccurs="0" maxOccurs="1"> <xsd:element ref="bean" /> <xsd:element ref="ref" /> <xsd:element ref="idref" /> <xsd:element ref="value" /> <xsd:element ref="null" /> <xsd:element ref="list" /> <xsd:element ref="set" /> <xsd:element ref="map" /> <xsd:element ref="props" /> <!-- Any XML --> <xsd:any namespace="##other" processContents="strict" /> </xsd:choice> </xsd:sequence> ... </xsd:complexType> </xsd:element>
Where the processContents attribitutes can have one of three values
strict: There must be a top-level declaration for the item available, or the item must have an xsi:type, and the item must be ·valid· as appropriate.
So, so long as your config XML has a schema, and you import it correctly, this should work.
Hope this helps
Wouldn't it be cleaner if your bean had a property telling it the location of the config file, and it loads the config from the classpath (or absolute location on the filesystem)? That way your Spring config looks cleaner and it's easier to edit the XML config of your bean since it's in a separate file.
Maybe you can even do this using the resources feature of the Spring Application Context.