Search code examples
javaspring-mvcjaxbjax-wscxf

Why doesn't JAXB allow annotations on getters that all pull from the same member variable?


Why does example A work, while example B throws a "JAXB annotation is placed on a method that is not a JAXB property" exception?

I'm using JAX-WS with Spring MVC.

Example A

package com.casanosa2.permissions;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

@XmlAccessorType(XmlAccessType.PROPERTY)
@XmlType(name = "FooXMLMapper")
public class FooXMLMapper implements IFoo {

 @XmlElement
 private final boolean propA;

 @XmlElement
 private final boolean propB;

 public FooMapper(IFoo foo) {
  propA = foo.getPropA()
  propB = foo.getPropB()
 }

 public FooMapper() {
  propA = false;
  propB = false;
 }

 @Override
 public boolean getPropA() {
  return propA;
 }

 @Override
 public boolean getPropB() {
  return propB;
 }
}

Example B

@XmlAccessorType(XmlAccessType.PROPERTY)
@XmlType(name = "FooXMLMapper")
public class FooXMLMapper {

 private final IFoo foo;

 public FooMapper() {
  foo = new IFoo() {

   @Override
   public boolean getPropA() {
    return false;
   }

   @Override
   public boolean getPropB() {
    return false;
   }

  };
 }

 public FooXMLMapper(IFoo foo) {
  this.foo = foo;
 }

 @XmlElement
 public boolean getPropA() {
  return foo.getPropA();
 }

 @XmlElement
 public boolean getPropB() {
  return foo.getPropB();
 }
}

Solution

  • I believe the accessors are ignored if it's looking directly at the instance variables and in your example B there are no actual instance variables of the right name. You have to tell it explicitly to use @XmlAccessorType(XmlAccessType.NONE) on the class and @XmlElement and @XmlAttribute on the get/set methods. At least, that's what I ended up doing with my JAXB mapping.