How to use @XmlSeeAlso annotation in JAX-WS


Friends the following udemy course created by me;

      Click here to attend Spring Framework 4.x and certification course with a discount

Spring Framework and Core Spring Certification Udemy course with discount
Spring Framework and Core Spring Certification Udemy course with a discount coupon

@XmlSeeAlso annotation is used to include custom classes (sub classes) inside client stubs (proxies). This annotation will modify the WSDL file and add a complex type automatically. By doing that, clients will have a complete stub classes .

Lets examine the following scenario;

public abstract class Product() {}
public class Phone extends Product() {}
public class Computer extends Product() {}

@WebService
@XmlSeeAlso({packagename.Phone.class, packagename.Computer.class})
public class MainWebService {

@WebMethod(operationName = “getTheProduct”)
public Product getTheProduct()   {

Product product = new Phone();

      //if you use XmlSeeAlso annotation
     //phone class can be created and returned without an error
//otherwise it will throw an exception in client proxies
//and JAX-WS will only create a Product class in client proxy
return product;

}
}
By adding @XmlSeeAlso annotation to the Web Service

All subclasses of the Product  class  (such as Phone and Computer) will be included inside client proxies so that any kind of casting can be done in these proxies. However if you do not include XMLSeeAlso annotation to your WebService, only the Product class will be included by JAXB and this won’t allow developers to use Phone or Computer classes’ fields and methods inside client proxies.

Sample error if you don’t use XMLSeeAlso annotation

Failed to read a response: javax.xml.bind.UnmarshalException – with linked exception: [javax.xml.bind.UnmarshalException: Unable to create an instance of package.Product – with linked exception: [java.lang.InstantiationException]]

Advertisements