I am trying to inject a JAXBContext
into spring application context, by:
<bean id="jaxbContext" class="javax.xml.bind.JAXBContext" factory-method="newInstance">
<constructor-arg type="java.lang.Class" value="com.package.MyClassName"/>
</bean>
It throws an exception:
No matching factory method found: factory method 'newInstance'
And I also try :
<bean id="jaxbContext" class="javax.xml.bind.JAXBContext" factory-method="newInstance">
<constructor-arg type="java.lang.String" value="com.package"/>
</bean>
And It throws an an exception:
javax.xml.bind.JAXBException: "com.package" doesnt contain ObjectFactory.class or jaxb.index I did put a jaxb.index file inside the package "com.package" and has a single line "MyClassName" in the file.
To use Spring's Jaxb2Marshaller, you will need the spring-oxm dependency, which you may already have, since it is used by other major spring components. To configure the Jaxb2Marshaller in your Spring context, add the config XML below. Be sure to add all root packages that contain the JAXB classes.
Spring BOOT is very smart and it can understand what you need with a little help. To make XML marshalling/unmarshalling work you simply need to add annotations @XmlRootElement to class and @XmlElement to fields without getter and target class will be serialized/deserialized automatically. Any questions are welcome.
JAXBContext is thread safe and should only be created once and reused to avoid the cost of initializing the metadata multiple times. Marshaller and Unmarshaller are not thread safe, but are lightweight to create and could be created per operation.
The JAXBContext class provides the client's entry point to the JAXB API. It provides an abstraction for managing the XML/Java binding information necessary to implement the JAXB binding framework operations: unmarshal, marshal and validate.
@Tomasz's answer is the solution I'd recommend, but if you want to stick with JAXBContext
, then the reason your first example failed is that the static getInstance()
method on JAXBContext
doesn't take a single Class
argument, it takes a vararg list of them. So you need to inject a list, not a single class:
<bean id="jaxbContext" class="javax.xml.bind.JAXBContext" factory-method="newInstance">
<constructor-arg value-type="java.lang.Class">
<list>
<value>com.package.MyClassName</value>
</list>
</constructor-arg>
</bean>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With