Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject JAXBContext into spring

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.

like image 321
yzandrew Avatar asked Mar 22 '11 05:03

yzandrew


People also ask

How do you use a Marshaller in spring?

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.

How do you Unmarshal XML to Java object in spring boot?

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.

Is JAXBContext thread safe?

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.

What is JAXBContext in Java?

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.


1 Answers

@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>
like image 124
skaffman Avatar answered Sep 18 '22 17:09

skaffman