自学内容网 自学内容网

在spring boot项目中使用jaxb实现Java Bean与XML互转

问题

在联调Web Service的过程中,需要经常处理Java Bean 与 XML互转。

解决

WsxxxConfiguration.java

package com.xxx.xxxx.wsdl;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;

@Configuration
public class WsxxxConfiguration {

    @Bean
    public Jaxb2Marshaller marshaller() {
        Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
        // this package must match the package in the <generatePackage> specified in
        // pom.xml
        // 这里主要是告诉jaxb需要解析xml与java bean相互转化的模型类在哪里
        marshaller.setPackagesToScan("com.xxx.xxxx.wsdl");
        return marshaller;
    }
}

这里主要是在Spring中配置jaxb,然后,使用这个marshaller来互转XML。

Java Bean转xml

...
 @Resource
    private Jaxb2Marshaller marshaller;
...
StringWriter xmlWriter = new StringWriter();
    marshaller.marshal(javabean, new StreamResult(xmlWriter));

这里主要适用marshal方法将Java bean转化成xml字符串。

参考:


原文地址:https://blog.csdn.net/fxtxz2/article/details/142459697

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!