问题

在联调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字符串。

参考:

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐