2010-04-22 12 views
9

Sto usando JAXB 2.0 JDK 6 per smantellare un'istanza XML in POJO.JAXB non chiama setter quando gli oggetti unmarshalling

Per aggiungere alcune convalide personalizzate, ho inserito una chiamata di convalida nel setter di una proprietà, ma nonostante sia privata, sembra che l'unmarshaller non chiami il setter ma modifichi direttamente il campo privato.

È fondamentale per me che la convalida personalizzata avvenga per questo specifico campo ogni chiamata unmarshall.

Cosa devo fare?

Codice:

@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; 
    } 
} 

risposta

13

JAXB utilizza l'accesso campo quanto è stato configurato in modo da utilizzare l'accesso campo annotando un campo con @XmlValue e dichiarando @XmlAccessorType(XmlAccessType.FIELD).

Per utilizzare l'accesso alla proprietà, è possibile spostare @XmlValue in getter o setter (@XmlAccessorType non è affatto necessario).

+0

Grazie ha fatto il trucco :) – Yaneeve

Problemi correlati