<dependency>
<groupId>jakarta.xml.ws</groupId>
<artifactId>jakarta.xml.ws-api</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.ws</groupId>
<artifactId>jaxws-rt</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>4.0.3</version>
</dependency>
备注: 如果XmlElement注解用在Java的属性上,该属性就不能出现getter和setter方法,否则运行出错
例如,下面片段XmlElement注解的属性name = "flag"指定了映射到xml中元素的名字是flag。如果不指定,xml元素的名字就会是functionCode:
@XmlElement(name = "flag")
private int functionCode;
例如:
@XmlElement(name = "flag")
public int getFunctionCode() {
return this.functionCode;
}
我感觉这种方法是灵活的,原因:
例如,下面用在getFunctionCode()方法上,设置了了映射到xml中的元素名称是flag:
private int functionCode;
@XmlElement(name = "flag")
public int getFunctionCode() {
return this.functionCode;
}
public void setFunctionCode(int functionCode) {
this.functionCode = functionCode;
}
在调用的地方设置属性的值:
RegisterResponse registerResponse = new RegisterResponse();
registerResponse.setFunctionCode(1);
例如,下面这段代码,XmlElement注解用在属性functionCode上,同时,有针对functionCode的getFunctionCode和setFunctionCode方法,运行就会出错,提醒有两个属性具有相同的名称(为了突出重点,调用的代码没有贴出来):
package com.thb.server.register;
import jakarta.xml.bind.annotation.XmlElement;
import jakarta.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "response")
public class RegisterResponse {
@XmlElement(name = "flag")
private int functionCode;
public RegisterResponse() {}
public int getFunctionCode() {
return this.functionCode;
}
public void setFunctionCode(int functionCode) {
this.functionCode = functionCode;
}
}
运行出错:
