我有一个春季启动项目。我的项目中有一些 xsd。我已经使用 maven-jaxb2-plugin 生成了这些类。我已经使用本教程来运行示例 Spring Boot 应用程序。
import org.kaushik.xsds.XOBJECT;
@SpringBootApplication
public class JaxbExample2Application {
public static void main(String[] args) {
//SpringApplication.run(JaxbExample2Application.class, args);
XOBJECT xObject = new XOBJECT('a',1,2);
try {
JAXBContext jc = JAXBContext.newInstance(User.class);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(xObject, System.out);
} catch (PropertyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JAXBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
但我担心的是我需要映射模式的所有 jaxb 类。Spring 中还有什么东西可以用来让我的任务更轻松。我查看了 Spring OXM项目,但它在 xml 中配置了应用程序上下文。弹簧靴有什么我可以开箱即用的东西吗?任何示例都会有所帮助。
编辑
我尝试了 xerx593 的答案,并使用 main 方法运行了一个简单的测试
JaxbHelper jaxbHelper = new JaxbHelper();
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setClassesToBeBound(XOBJECT.class);
jaxbHelper.setMarshaller(marshaller);
XOBJECT xOBJECT= (PurchaseOrder)jaxbHelper.load(new StreamSource(new FileInputStream("src/main/resources/PurchaseOrder.xml")));
System.out.println(xOBJECT.getShipTo().getName());
它运行得非常好。现在我只需要使用 spring boot 将其插入即可。