2010-04-22 2 views
9

J'utilise JAXB 2.0 JDK 6 pour démasquer une instance XML dans POJOs. Pour ajouter une validation personnalisée, j'ai inséré un appel de validation dans le setter d'une propriété, mais malgré le fait qu'il soit privé, il semble que le unmarshaller n'appelle pas le setter mais modifie directement le champ privé.JAXB n'appelle pas setter lors d'unmarshalling d'objets

Il est crucial pour moi que la validation personnalisée se produise pour ce champ spécifique à chaque appel unmarshall.

Que dois-je faire?

code:

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

Répondre

13

JAXB utilise l'accès sur le terrain parce que vous avez configuré pour utiliser l'accès sur le terrain par annoter un champ avec @XmlValue et en déclarant @XmlAccessorType(XmlAccessType.FIELD).

Pour utiliser l'accès aux propriétés, vous pouvez déplacer @XmlValue vers getter ou setter (@XmlAccessorType n'est pas nécessaire du tout).

+0

Merci a fait l'affaire :) – Yaneeve