在解组对象时,JAXB不会调用setter

Yan*_*eve 9 java setter jaxb customvalidator

我正在使用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;
    }
}
Run Code Online (Sandbox Code Playgroud)

axt*_*avt 14

JAXB使用字段访问,因为您通过使用@XmlValue和通过声明来注释字段来将其配置为使用字段访问@XmlAccessorType(XmlAccessType.FIELD).

要使用属性访问,您可以移动@XmlValue到getter或setter(@XmlAccessorType根本不需要).