Monday, December 8, 2008

Using JAXB in a Spring-Maven Environment for WebServices

In a Spring application you can consume a webservice using JaxRpcPortProxyFactorybean or XFireClientFactoryBean (in conjunction with XFire). However, there is another way which can prove to be extremely useful and convenient if you are using Spring and Maven: by using Spring and Maven in conjunction with JAXB. As usual, I will focus on using JAXB and not about JAXB. To learn more about JAXB see:


In this article we will cover
1. Setting up JAXB in Spring environment to generate stubs for the webservice
2. Using it in an external project or the same project.

As per the default maven build structure, you need to make a package called "wsdl" under src/main and place a copy of wsdl of the webservice you wish to use. Then configure your pom file with the right dependencies:



Two things that you should notice in the pom besides JAXB dependencies are the build plugins maven-source-plugin and maven-jaxb2-plugin. They will generate stubs for your webservice in the "target" directory under "generated-sources" when you compile the project/ generate resources using maven. After that your webservice should be ready to used. Almost :D.

The generated source will contain stubs that correspond to exposed functions, responses and the various objects used. The name of the stubs will correspond to name in wsdl. In the same project you can use it by importing stubs from the package specified in com.saveenkumar.myApp.someWebService.types For an external project, you just need to import the project as a dependency.

Let us now see how to use these stubs. You will be able to use the webservice in your Spring app with the help of org.springframework.ws.client.core.WebServiceTemplate. You can see the bean config that you can use to inject it here:


Note that the "contextPaths" property of the JAXB marshaller is same as the  property above. If you want to dig still deeper, have a look about using WebServiceTemplate  at:


and



It may be a good idea to hide the WebServiceTemplate behind a nice interface to abstract away the user from the generated JAXB classes.

The generated classes will always have a class called "ObjectFactory". There will also be objects corresponding to every operation, every response and every object used in these transactions. Let us say our webservice exposes the following operations:

List getAllStockInfo();
List getStocksByVolatilityRange(float low, float high);
StockInfo getStockInfo(String ticker);

May generate following objects:

ObjectFactory
ArrayOfStockInfo
StockInfo
GetAllStockInfo
GetAllStockInfoResponse
GetStockInfo
GetStockInfoResponse
GetStocksByVolatilityRange
GetStocksByVolatilityRangeResponse

Let us say we want to use GetStockInfo. The code would look something like:



I would also recommend using SoapUI to test your webservices. 

No comments: