9

我正在使用 JAXB 2.0 JDK 6 将 XML 实例解组为 POJO。

为了添加一些自定义验证,我在属性的设置器中插入了一个验证调用,尽管它是私有的,但解组器似乎没有调用设置器,而是直接修改了私有字段。

对我来说至关重要的是,每次 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;
    }
}
4

1 回答 1

15

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

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

于 2010-04-22T11:30:04.127 回答