Spring: Injecting JAXB (Un)Marshaller
Create a JAXB context passing an array of root element classes:
<bean id="jaxbContext" class="javax.xml.bind.JAXBContext" factory-method="newInstance"> <constructor-arg> <list> <value type="java.lang.Class">my.example.rootclass.Root</value> </list> </constructor-arg> </bean>
Create prototypes for the marshallers/unmarshallers
<!-- Pool (un)marshallers to improve performance --> <bean id="marshallerTarget" class="javax.xml.bind.Marshaller" factory-bean="jaxbContext" factory-method="createMarshaller" scope="prototype"> </bean> <bean id="unmarshallerTarget" class="javax.xml.bind.Unmarshaller" factory-bean="jaxbContext" factory-method="createUnmarshaller" scope="prototype"> </bean>
Wrap these in pool targets:
<bean id="poolTargetSource" class="org.springframework.aop.target.CommonsPoolTargetSource"> <property name="targetBeanName" value="marshallerTarget" /> <property name="maxSize" value="25" /> </bean> <bean id="unmarshallerPoolTargetSource" class="org.springframework.aop.target.CommonsPoolTargetSource"> <property name="targetBeanName" value="unmarshallerTarget" /> <property name="maxSize" value="25" /> </bean>
And create pools for reusing marshallers/unmarshallers:
<bean id="marshaller" class="org.springframework.aop.framework.ProxyFactoryBean"> <qualifier value="marshaller" /> <property name="targetSource" ref="poolTargetSource" /> </bean> <bean id="unmarshaller" class="org.springframework.aop.framework.ProxyFactoryBean"> <qualifier value="unmarshaller" /> <property name="targetSource" ref="unmarshallerPoolTargetSource" /> </bean>
This will create one context that will be used to create up to 25 marshallers/unmarshallers. Each will be created on demand until there are 25 in use simultaneously, then calls to them will block until one becomes available. Be careful changing the state on the (un)marshallers. It would probably be a better idea to create prototypes for each configuration and inject a separate pool for each.
These can be injected in the application context or using annotations:
@Autowired
@Qualifier("unmarshaller")
private Unmarshaller unmarshaller;
@Autowired
@Qualifier("marshaller")
private Marshaller marshaller;
Advertisement
thank you – you helped me a lot
best regards,
michal
Thanks for the tip,
but how do you create a jaxbcontext which can handle multiple packages?
Multiple packages? Do you mean multiple root element classes? Simply add another root element class to the constructor-arg list.
It’s the best jaxb usaged I have seen
thanks
Very nice sir!
To the point….. exactly what I was looking for.