近期在进行老架构迁移的时候,原先的webservice接口需要迁移至新架构,之前使用的xml框架是xfile,后来要改成cxf,该项目是springboot+maven项目(前提)。
接口测试选择SoapUI:
首先看下原先老架构访问webservice接口生成的xml:
老架构生成的xml返回参数有String类型和Collection两种。本以为这样迁移到新架构就OK了,但是没想到用SoapUI访问新链接以后出问题了!!!
下边是新架构访问webservice接口生成的xml:
原本使用xfile生成的参数有四个,就算参数为空,返回也是一个空的标签(这里是因为自定义了xml的生成规则),但是cxf好像并不简单。
这个原因是因为CXF在解析Bean到xml时,如果传入参数是null,或自动隐藏该标签,所以那个responseL1标签是null的时候,是不会显示的。然后自己搞几个数据进去,果然是可以显示。有一种办法说加XMLAdapter适配器,然后自定义,当参数为null或者"“时,将值换成” "(中间有空格),这样在解析的时候就不会出现标签不显示的情况,但是我试了,没用。再找!!
利用XMLAdapter解决方法
然后无意中在网上发现可以利用javax.xml.bind.annotation包下的注解自定义xml生成规则,搞起来!
首先在实体类上添加@XmlRootElement注解,然后在每个getter方法添加@XmlElement(nillable = true),注意,我第一次是给每一个变量的getter方法添加的都是这个注解,如果参数是List类型,那么这个注解是不生效的,需要使用@XmlElementWrapper(nillable = true)对List类型的参数生效。
JAXB常用注解讲解
重点在于要添加属性:nillable属性可以指定元素的文本值是否可以为空,默认为false。这样就OK啦。
添加注解后的Custom.java
@XmlRootElement(name="Custom")
public class Custom {
private String response1;
private String response2;
private String response3;
private List<Student> responseL1;
@XmlElement(name = "response3",nillable = true)
public final String getResponse3() {
return response3;
}
public final void setResponse3(String response3) {
this.response3 = response3;
}
@XmlElement(name = "response1",nillable = true)
public final String getResponse1() {
return response1;
}
public final void setResponse1(String response1) {
this.response1 = response1;
}
@XmlElement(name = "response2",nillable = true)
public final String getResponse2() {
return response2;
}
public final void setResponse2(String response2) {
this.response2 = response2;
}
@XmlElementWrapper(name = "responseL1",nillable = true)
public final List<Student> getResponseL1() {
return responseL1;
}
}
关于XML注解可以参考以下链接
https://www.cnblogs.com/Eric-Hello/p/7452913.html
然后重启项目(注意:每次发布webservice接口都需要重启才能生效)
展示下修改后的xml测试结果:
打完收工。