[英]JAXB does not call setter when unmarshalling objects
我正在使用JAXB 2.0 JDK 6來將XML實例解組為POJO。
為了添加一些自定義驗證,我已經將一個驗證調用插入到屬性的setter中,盡管它是私有的,但似乎unmarshaller不會調用setter但直接修改私有字段。
對我來說,每個unmarshall調用都會針對此特定字段進行自定義驗證,這一點至關重要。
我該怎么辦?
碼:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "LegalParams", propOrder = {
"value"
})
public class LegalParams {
private static final Logger LOG = Logger.getLogger(LegalParams.class);
@XmlTransient
private LegalParamsValidator legalParamValidator;
public LegalParams() {
try {
WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
LegalParamsFactory legalParamsFactory = (LegalParamsFactory) webApplicationContext.getBean("legalParamsFactory");
HttpSession httpSession = SessionHolder.getInstance().get();
legalParamValidator = legalParamsFactory.newLegalParamsValidator(httpSession);
}
catch (LegalParamsException lpe) {
LOG.warn("Validator related error occurred while attempting to construct a new instance of LegalParams");
throw new IllegalStateException("LegalParams creation failure", lpe);
}
catch (Exception e) {
LOG.warn("Spring related error occurred while attempting to construct a new instance of LegalParams");
throw new IllegalStateException("LegalParams creation failure", e);
}
}
@XmlValue
private String value;
/**
* Gets the value of the value property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getValue() {
return value;
}
/**
* Sets the value of the value property.
*
* @param value
* allowed object is
* {@link String }
* @throws TestCaseValidationException
*
*/
public void setValue(String value) throws TestCaseValidationException {
legalParamValidator.assertValid(value);
this.value = value;
}
}
JAXB使用字段訪問,因為您通過使用@XmlValue
注釋字段並聲明@XmlAccessorType(XmlAccessType.FIELD)
來將其配置為使用字段訪問。
要使用屬性訪問,可以將@XmlValue
移動到getter或setter(根本不需要@XmlAccessorType
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.