Inject JAXBContext into spring

yzandrew picture yzandrew · Mar 22, 2011 · Viewed 21.1k times · Source

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.

Answer

skaffman picture skaffman · Mar 22, 2011

@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>