将JAXBContext注入spring

yza*_*rew 19 spring jaxb code-injection

我试图通过以下方式注入JAXBContextspring应用程序上下文:

<bean id="jaxbContext" class="javax.xml.bind.JAXBContext" factory-method="newInstance">
  <constructor-arg type="java.lang.Class" value="com.package.MyClassName"/>
</bean>
Run Code Online (Sandbox Code Playgroud)

它引发了一个异常:

找不到匹配的工厂方法:工厂方法'newInstance'

我也尝试:

<bean id="jaxbContext" class="javax.xml.bind.JAXBContext" factory-method="newInstance">
  <constructor-arg type="java.lang.String" value="com.package"/>
</bean>
Run Code Online (Sandbox Code Playgroud)

它引发了一个例外:

javax.xml.bind.JAXBException:"com.package"不包含ObjectFactory.class或jaxb.in​​dex我确实在包"com.package"中放了一个jaxb.in​​dex文件,并在文件中有一行"MyClassName".

ska*_*man 15

@ Tomasz的答案是我推荐的解决方案,但是如果你想坚持下去JAXBContext,那么你的第一个例子失败的原因是static getInstance()方法onJAXBContext不带一个Class参数,它需要一个vararg列表.所以你需要注入一个列表,而不是一个类:

<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>
Run Code Online (Sandbox Code Playgroud)

  • 实际上`getInstance()`接受一个`Class`参数([见文档](http://docs.oracle.com/javase/6/docs/api/javax/xml/bind/JAXBContext.html)),所以像`<constructor-arg> <value type ="java.lang.Class"> com.package.MyClassName </ value> </ constructor-arg>`这样的东西也可以. (3认同)

Tom*_*icz 11

你试过Spring OXM吗?最后一行很重要,命名空间仅供参考:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:oxm="http://www.springframework.org/schema/oxm"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-1.5.xsd">

    <oxm:jaxb2-marshaller id="marshaller" contextPath="com.package"/>
</beans>
Run Code Online (Sandbox Code Playgroud)

8.4.基于XML模式的配置.你还需要spring-oxm在你的课堂上.