/, Web Services/Spring Web Services Tutorial

Spring Web Services Tutorial

I’ve recently written a more up to date version of this post which describes how to build a contract first web service using Apache CXF. Check it out here.

SOAP Services

Modern enterprise applications are rarely stand alone and often rely on data and services provided by external systems. In order for different types of systems to communicate there must be a  communication protocol of some sort, a standard way of sending and receiving messages in a format that is recognised and supported by all major platforms. SOAP (Simple Object Application Protocol) is such a protocol, and allows applications to communicate by exchanging messages in a standard XML format.
SOAP Web Services provide a platform agnostic integration mechanism that allows disparate systems to exchange data regardless of the platform they are running on. For example, SOAP web services are commonly used to integrate .NET applications with applications running on the Java platform. Almost all modern platforms and frameworks (Java, .Net, Ruby, PHP, etc) provide comprehensive libraries and tooling that allow developers to quickly and easily expose and consume SOAP services.
This post will look at Spring Web Services and take you through a step by step tutorial for building, deploying and testing a simple contract first SOAP service for retrieving simple bank account details.

Tech Stack

The technology stack used in this tutorial will include Spring 3.1 for Web Services Support, Maven for  dependency resolution & build, Tomcat for our test server and SoapUI to build sample SOAP messages for testing our service.

Creating the Project

The project structure is similar to that used in a some of my other tutorials and is typical of most modern Spring web applications. We’ll start off by creating a simple Spring web project like the one shown in figure 1.0 below.

Figure 1.0 Project Structure

Contract Last vs Contract First

There are two fundamental approaches to building web services, Contract Last and Contract First. The Contract Last approach involves taking existing code and generating a service contract directly from that code in order to expose it as a SOAP interface. There are a variety of Java frameworks out there (Axis2, XFire etc) that provide this Java2WSDL tooling, to quickly generate the server side proxies, marshallers and Servlet classes required to expose a SOAP service.
The Contract First approach involves defining the Service contract before implementing the service. This means describing the service parameters and return types using XSD’s (XML Schema Definitions), then using those XSD’s to construct a WSDL (web service definition language) to provides a public facing contract or description of the service. Only after the service contract has been clearly defined, is the service implementation actually written.
This post will describe a Contract First service, as this is the preferred approach for various reasons, some of which are explained in this article.

Service Contract Definition

Given that we’re building a service to retrieve simple bank account details we’ll start off by defining our core business entity, an Account. We’ll define our account entity in src/main/webapp/schemas/AccountDetails.xsd.

<?xml version="1.0" encoding="UTF-8"?>  
 <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://webservices.samples.blog.com" targetNamespace="http://webservices.samples.blog.com" elementFormDefault="qualified" attributeFormDefault="unqualified">  
      <xs:element name="Account" type="Account"/>  
      <xs:complexType name="Account">  
                <xs:element name="AccountNumber" type="xs:string"/>  
                <xs:element name="AccountName" type="xs:string"/>  
                <xs:element name="AccountBalance" type="xs:double"/>  
                <xs:element name="AccountStatus" type="EnumAccountStatus"/>  
      <xs:simpleType name="EnumAccountStatus">  
           <xs:restriction base="xs:string">  
                <xs:enumeration value="Active"/>  
                <xs:enumeration value="Inactive"/>  

I use XMLSpy for working with XML as it provides a useful graphical representation of the XML types being defined. This can be useful when working on large applications with complex data models. A visual representation of the above XSD is shown below.

Figure 2.0 Account Entity

Next we’ll define the service request and response types in src/main/webapp/schemas/AccountDetailsServiceOperations.xsd.

<?xml version="1.0" encoding="UTF-8"?>  
 <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://com/blog/samples/webservices/accountservice" xmlns:account="http://webservices.samples.blog.com" targetNamespace="http://com/blog/samples/webservices/accountservice" elementFormDefault="qualified">  
      <xsd:import namespace="http://webservices.samples.blog.com" schemaLocation="AccountDetails.xsd"/>  
      <xsd:element name="AccountDetailsRequest">  
                     <xsd:element name="accountNumber" type="xsd:string"/>  
      <xsd:element name="AccountDetailsResponse">  
                     <xsd:element name="AccountDetails" type="account:Account"/>  

A visual representation of these types is shown below.

Figure 3.0 AccountDetailsRequiest Entity


Figure 4.0 AccountDetailsResponse Entity

Object to XML Mapping

A fundamental part of web services is the conversion of SOAP messages from XML to Java objects and vice versa. This is a non trivial task if you were to set out to do it yourself so we’ll make use of the JAXB framework to take car of this for us. I’ve been working with JAXB for a few years now and find it to be a powerful and flexible framework, and a huge improvement on older OXM frameworks like Castor.
In order to use our XSD defined types in the application we need to generate Java classes from those types. We do this as part of the Maven build process by using the jaxb-maven-plugin in our POM. The plugin is configured to parse a set of XSD’s and run JAXB’s class generator to create Java classes for each of the defined types. For brevity only part of the Maven POM definition is shown below. The entire  POM definition can be found with the source code that accompanies this tutorial.

<?xml version="1.0"?>  
 <project xmlns="http://maven.apache.org/POM/4.0.0"  

Running a Maven build will create Java classes for each of the defined schema types. The screenshot below shows what the generated classes should look like in your project after you run a Maven build. Note that JAXB has used the the namespaces in the XSD’s to derive package names for the generated classes.

Figure 5.0 JAXB Generated Classes

Defining the Service

The next step is to define the Service interface using the types we generated above. The Service interface is defined below and is very simple indeed.

package com.blog.samples.services;  
import com.blog.samples.webservices.Account;  
 * The Interface AccountService.  
public interface AccountService  
      * Gets the account details.  
      * @param accountNumber the account number  
      * @return the account details  
     public Account getAccountDetails(String accountNumber);  

Now we’ll provide a really simple implementation of this interface. As you can see our service implementation returns some hard coded values. Obviously a real service implementation would do something more meaningful.

package com.blog.samples.services;  
 import org.springframework.stereotype.Service;  
 import com.blog.samples.webservices.Account;  
 import com.blog.samples.webservices.EnumAccountStatus;  
  * The Class AccountService.  
 public class AccountServiceImpl implements AccountService  
       * Gets the account details.  
       * @param accountNumber the account number  
       * @return the account details  
      public Account getAccountDetails(String accountNumber)  
           /* hard coded account data - in reality this data would be retrieved  
            * from a database or back end system of some sort */  
           Account account = new Account();  
           account.setAccountName("Joe Bloggs");  
           return account;  

Creating the Service Endpoint

A service endpoint is the component that deals with processing web service requests and responses. In the background a Spring Servlet intercepts incoming SOAP requests for a defined URL and routes them to an endpoint for processing. Below we’re going to define that endpoint.

package com.blog.samples.services.endpoints;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.ws.server.endpoint.annotation.Endpoint;  
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;  
import org.springframework.ws.server.endpoint.annotation.RequestPayload;  
import org.springframework.ws.server.endpoint.annotation.ResponsePayload;  
import com.blog.samples.services.AccountService;  
import com.blog.samples.webservices.Account;  
import com.blog.samples.webservices.accountservice.AccountDetailsRequest;  
import com.blog.samples.webservices.accountservice.AccountDetailsResponse;  
 * The Class AccountService.  
public class AccountServiceEndpoint  
  private static final String TARGET_NAMESPACE = "http://com/blog/samples/webservices/accountservice";  
  private AccountService accountService_i;  
   * Gets the account details.  
   * @param accountNumber the account number  
   * @return the account details  
  @PayloadRoot(localPart = "AccountDetailsRequest", namespace = TARGET_NAMESPACE)  
  public @ResponsePayload AccountDetailsResponse getAccountDetails(@RequestPayload AccountDetailsRequest request)  
    AccountDetailsResponse response = new AccountDetailsResponse();  
    /* call Spring injected service implementation to retrieve account data */  
    Account account = accountService_i.getAccountDetails(request.getAccountNumber());  
    return response;  
  public void setAccountService(AccountService accountService_p)  
    this.accountService_i = accountService_p;  

Our sample application makes sue of  Springs Web Services annotation support. The above class uses a number of these annotations, each of which is explained below.

Line 14 – @Enpoint is a specialised version of the standard Spring @Component annotation and allows this class to get picked up and registered by Springs component scanning.
Lines 19 & 20 – Our simple service implementation is Spring injected so that it can be used by our web service endpoint.
Line 17 – this is the namespace we defined in our XSD type definitions earlier. We use this in the endpoint class for mapping request to specific methods for processing.
Line 28 – @PayloadRoot indicates that this method will process service requests with the XML root element matching that defined by the localPart attribute. In the example above our method will process incoming requests of type AccountDetailsRequest with namespace http://com/blog/samples/webservices/accountservice. Remember that we defined this XSD type and namespace earlier.
Line 29 – @ResponsePayload indicates the type to be returned in the SOAP response. In this example the AccountDetailsResponse object will be converted to XML and returned to the client application as a SOAP response. @RequestPayload AccountDetails tells Spring to convert incoming requests of type AccountDetails, from XML to Java and the pass that object as a parameter to this endpoint method.

Spring Configuration

Next we’ll write our Spring configuration to bring everything together. The Spring configuration is defined as follows.

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
      <context:component-scan base-package="com.blog.samples.services" />  
      <sws:annotation-driven />  
           Our test service bean  
      <bean id="AccountDetailsService" class="org.springframework.ws.wsdl.wsdl11.DefaultWsdl11Definition" lazy-init="true">
      <property name="schemaCollection">  
       <bean class="org.springframework.xml.xsd.commons.CommonsXsdSchemaCollection">  
         <property name="inline" value="true" />  
         <property name="xsds">  
      <property name="portTypeName" value="AccountDetailsService"/>  
      <property name="serviceName" value="AccountDetailsServices" />  
      <property name="locationUri" value="/endpoints"/>  
  • Line 13 – Component scanning scans the defined package (com.blog.sample.services) for Spring managed components to load into the bean factory.
  • Line 14 – Enables Spring Web Services annotation support so that annotations like @PayloadRoot can be used to configure the service endpoint.
  • Line 20 to 33 – Use of DefaultWsdl11Definition enables automated WSDL generation. Spring uses the schema definitions listed in the schemaCollection property, as well as the portType, serviceName and locationUri to generate a WSDL file the first time it is requested. Although this is a powerful feature it should be used with caution in production as the WSDL generation process can be quite slow. An approach I’ve used in the past is to copy the generated WSDL from your browser to your project and expose it using Springs static WSDL support with <static-wsdl>.


Now for the final bit of configuration before we test out our service. Web.xml is defined as follows.

<?xml version="1.0" encoding="UTF-8"?>  
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
           xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
  • Line 8 to 13 – Path for Spring configuration to be loaded on application start-up.
  • Line 14 to 16 – Loads the Spring application context using the configuration file defined above
  • Line 18 to 19 – Spring Web Service Servlet that intercepts incoming HTTP requests.
  • Line 21 to 22 – Ensures WSDL is context aware. Transforms SOAP address so that it isn’t hard coded to localhost:8080.Address updates depending on the application context and port that the application is deployed at.
  • Line 25 to 26 – ContextConfigLocation set with an empty parameter means that Spring won’t try to load the default webservices-servlet.xml configuration.
  • Line 35 to 36 – Configures the URLs that our newly configured Web Services Servlet will handle.

Deploying the Service

We’re now ready to deploy our application – I use Tomcat but feel free to use any Servlet container. Once the application is deployed, just browse to http://localhost:8080/spring-webservices-sample/endpoints/AccountDetailsService.wsdl and the application should generate and display the following WSDL.

<wsdl:definitions xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:sch0="http://com/blog/samples/webservices/accountservice" xmlns:sch
          <xsd:schema xmlns="http://com/blog/samples/webservices/accountservice" xmlns:account="http://webservices.samples.blog.com" xmln
               <xsd:import namespace="http://webservices.samples.blog.com"/>  
               <xsd:element name="AccountDetailsRequest">  
                              <xsd:element name="accountNumber" type="xsd:string"/>  
                <xsd:element name="AccountDetailsResponse">  
                               <xsd:element name="AccountDetails" type="account:Account"/>  
           <xs:schema xmlns="http://webservices.samples.blog.com" xmlns:xs="http://www.w3.org/2001/XMLSchema" attributeFormDefault="unqua
                <xs:element name="Account" type="Account"/>  
                <xs:complexType name="Account">  
                          <xs:element name="AccountNumber" type="xs:string"/>  
                          <xs:element name="AccountName" type="xs:string"/>  
                          <xs:element name="AccountBalance" type="xs:double"/>  
                          <xs:element name="AccountStatus" type="EnumAccountStatus"/>  
                <xs:simpleType name="EnumAccountStatus">  
                     <xs:restriction base="xs:string">  
                          <xs:enumeration value="Active"/>  
                          <xs:enumeration value="Inactive"/>  
      <wsdl:message name="AccountDetailsResponse">  
           <wsdl:part element="tns:AccountDetailsResponse" name="AccountDetailsResponse"/>  
      <wsdl:message name="AccountDetailsRequest">  
           <wsdl:part element="tns:AccountDetailsRequest" name="AccountDetailsRequest"/>  
      <wsdl:portType name="AccountDetailsService">  
           <wsdl:operation name="AccountDetails">  
                <wsdl:input message="tns:AccountDetailsRequest" name="AccountDetailsRequest"/>  
                <wsdl:output message="tns:AccountDetailsResponse" name="AccountDetailsResponse"/>  
      <wsdl:binding name="AccountDetailsServiceSoap11" type="tns:AccountDetailsService">  
           <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>  
           <wsdl:operation name="AccountDetails">  
                <soap:operation soapAction=""/>  
                <wsdl:input name="AccountDetailsRequest">  
                     <soap:body use="literal"/>  
                <wsdl:output name="AccountDetailsResponse">  
                     <soap:body use="literal"/>  
      <wsdl:service name="AccountDetailsServices">  
           <wsdl:port binding="tns:AccountDetailsServiceSoap11" name="AccountDetailsServiceSoap11">  
                <soap:address location="http://localhost:8080/spring-webservices-sample/endpoints"/>  

Testing the Service

The simplest way to test a SOAP service is using SoapUI. For anyone who hasn’t used it before, SoapUI is an open source functional testing tool for testing SOAP web services. It saves us having to write a web service client and means that in just a few clicks we can have a test harness in place to test our service.

To test our serviced using SoapUI follow the steps below.

Figure 6.0 SoapUI Test Project

  • SoapUI will parse the exposed WSDL (make sure your application is deployed and the WSDL is exposed!) and use it to build a sample SOAP request.
  • When the new project opens click AccountServiceTest -> AccountDetails -> request and you’ll see a SOAP request for the AccountDetails service in the left hand pane. Set the account number and press the green arrow in the top left hand corner to call the service.
  • If the request is successful you should see a SOAP response containing the requested account data in the right hand pane. See figure 7.0 below

Figure 7.0 SoapUI AccountDetaills Service Test

Wrapping Up

The sample code in this post took you through the steps required to build, deploy and test a contract first web service using the Spring framework. Don’t forget that you can download the full source code for this tutorial and play around with it. If you found this tutorial useful then feel free to share it with others or leave a comment below. The full source code can be found on GitHub at https://github.com/briansjavablog/spring-webservices-tutorial.
By |2019-02-20T17:03:03+00:00January 14th, 2013|Spring, Web Services|118 Comments


  1. Anshul 4th February 2013 at 11:00 am - Reply

    the best tutorial ever worked , thank you sir

    it really helped …all other blogs sucks for thier tutorial even spring official framework developers especially arjen !! 🙂

  2. Brian 4th February 2013 at 11:34 am - Reply

    Thanks Anshul, glad you liked it.

  3. Pavan Kumar 8th February 2013 at 8:29 am - Reply

    This comment has been removed by the author.

  4. Pavan Kumar 8th February 2013 at 8:32 am - Reply

    HI, Brian,
    It was very helpful for me in easy understanding the Spring WS.
    Even i had gone threw many blogs. I didn't got the detailed explanation like this..
    Keep on blogging the new technologies ……
    Thanks once again..

  5. Ammar 9th February 2013 at 1:35 am - Reply

    Thank you so much.
    Great Tutorial.

  6. nityanandasahoo 9th February 2013 at 7:54 pm - Reply

    It is nice but you have not developed the client……..i need the client also.please post it.

  7. Pankaj Verma 4th March 2013 at 12:40 am - Reply

    A very nice and comprehensive tutorial. Admire the beautiful presentation style and completeness!
    Great job and, of course, Many Thanks for taking the pains to put this up.

  8. Skubanek 7th March 2013 at 9:17 am - Reply

    I spend a day searching for something like this – thanks a lot for the detailed explanations provided.

  9. Venkatraman 14th March 2013 at 5:03 pm - Reply

    Awesome tutorial:) Thank you so much. If possible can you develop a client too for this?

  10. Brian 14th March 2013 at 5:31 pm - Reply

    I've posted an Axis2 web service client tutorial here

  11. casimirrex antony 22nd March 2013 at 6:49 am - Reply

    Hi This source code does not available in following url(https://github.com/briansjavablog/spring-webservices-tutorial)

    Pls ensure and give and actual soure code url


  12. Ernesto Diaz 22nd March 2013 at 11:36 am - Reply

    This is an outstanding job! First example (I found) that really works, I hope someone will put it on the official Spring site. Thanks!!

  13. Brian 22nd March 2013 at 9:37 pm - Reply

    I just checked the link and it works fine.

  14. Vijay Prakash Vyas 23rd March 2013 at 11:13 pm - Reply

    Gr8 job Brian, Using above sample I converted my existing WS project from Cxf to Spring based.

  15. shivam verma 26th March 2013 at 8:57 am - Reply

    Hey, i have read this one . Its really great.

    One thing, if you could just help out!!!

    How do we access , these web services through our java classes.

    I mean simply from any java class/servlet , how do i send a particular request, and immediately recieve a response as well. !!!!

  16. Brian 26th March 2013 at 12:29 pm - Reply

    Sounds like you're looking for a web service client – you can see an example here using Axis2.

  17. shivam verma 27th March 2013 at 9:35 am - Reply

    hello brian , i am thinking of accessing the web service through url. i mean both applications are different. And i want to access it through sending a request.

    Moreover, i would also like to have a word from you. On just letting me know, if Spring web service would be good for usage or packages like these — apache axis, raw jax , ….Etc. you can specify too.

    That would be a appreciated guided help. !!!

  18. shivam verma 27th March 2013 at 9:43 am - Reply

    ok , i think i sort of overlooked your reply , your sample…. Well, i see it is sort of a client… But then that is almost very complex thing….

    another thing, while making the web service , as i was.. i had in my head. That it would be something standalone. ANd accessable directly via url's … Well, one more thing, the way you are depicting — > is it the standard protocol/ or are there any other methods as well…

    Guided Help would be highly appreciated …

  19. test 31st March 2013 at 11:20 pm - Reply

    Very good tutorial

  20. Raúl Garcia 1st April 2013 at 7:46 pm - Reply

    This comment has been removed by the author.

  21. neel4Tech 5th April 2013 at 10:48 am - Reply

    Very nice explanation, thanks a lot 🙂

  22. Binu 13th April 2013 at 9:42 am - Reply


    Very good explanation. I ran this in Ubuntu 11.10, Spring.
    Source Tool Suite. Worked without any major problem. Somehow it is not able to detect the spring-context.xml at /WEB-INF/conf location.

    I just moved that into /WEB-INF location. It worked then.

    Thanks a lot

  23. rahul urama 27th April 2013 at 6:11 pm - Reply

    great..awesome tutorial

  24. ddd 27th April 2013 at 10:34 pm - Reply

    Hi Brian,

    i got the following error/exception when i tried to deploy the project to Tomcat:Any idea how to solve it..

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'AccountDetailsService' defined in ServletContext resource [/WEB-INF/config/spring-config.xml]: Initialization of bean failed; nested exception is java.lang.NoClassDefFoundError: org/apache/ws/commons/schema/resolver/URIResolver
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:527)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:400)
    at org.springframework.context.support.AbstractApplicationContext.getBeansOfType(AbstractApplicationContext.java:1164)
    at org.springframework.beans.factory.BeanFactoryUtils.beansOfTypeIncludingAncestors(BeanFactoryUtils.java:275)
    at org.springframework.beans.factory.BeanFactoryUtils.beansOfTypeIncludingAncestors(BeanFactoryUtils.java:279)
    at org.springframework.ws.transport.http.MessageDispatcherServlet.initWsdlDefinitions(MessageDispatcherServlet.java:385)
    at org.springframework.ws.transport.http.MessageDispatcherServlet.initFrameworkServlet(MessageDispatcherServlet.java:231)
    at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:307)
    at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:127)
    at javax.servlet.GenericServlet.init(GenericServlet.java:160)
    at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1280)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1193)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1088)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5123)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5407)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
    at java.util.concurrent.FutureTask.run(FutureTask.java:166)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    at java.lang.Thread.run(Thread.java:722)
    Caused by: java.lang.NoClassDefFoundError: org/apache/ws/commons/schema/resolver/URIResolver

  25. Brian 29th April 2013 at 7:26 am - Reply

    It looks like Tomcat can't find org.apache.ws.commons.schema.resolver.URIResolver.class. This class should be included in XmlSchema version 1.4.3. (set up as a POM dependency with artifact Id XmlSchema).

  26. Chandu Chinthala 2nd May 2013 at 3:08 am - Reply

    Hi Brain,

    It is a nice tutorial for creating a web-service. I am following the exact steps mentioned, but after generating Java classes that are related to XSD/schema, somehow Java files are unable to any of the

    javax.xml.bind.* classes like XmlType, XmlAccessType.. etc. I tried adding below dependancies to pom.xml



    Then the compilation errors are gone, but while accessing the service I am facing like " org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.ws.server.endpoint.adapter.method.SourcePayloadMethodProcessor]: Constructor threw exception; nested exception is java.lang.ClassCastException: com.sun.xml.stream.ZephyrParserFactory "

    You have any idea?.. Do we really need the dependencies I have added or the dependacies you have in your example are enough?..

    thanks for your help

  27. ddd 6th May 2013 at 2:26 pm - Reply

    You're right. somehow i was missing the XmISchema dependency from my pom. my fualt!…thanks for the reply!

  28. Brian Heisler 24th May 2013 at 7:41 pm - Reply

    Excellent work, well done – thanks!

  29. Georgian Micsa 4th June 2013 at 9:36 pm - Reply


    I`m using apache-tomcat-6.0.37, jdk1.6.0_45 and SOAPUI 4.5.2. Although I can access the WSDL in the browser, importing it in SOAPUI fails with
    Error loading [http://localhost:8080/spring-webservices-sample/endpoints/AccountDetailsService.wsdl]: java.lang.Exception: Failed to load url; http://localhost:8080/spring-webservices-sample/endpoints/AccountDetailsService.wsdl but no exception in the logs.
    I also tried to save the WSDL in a file and import it in SOAPUI but when I call the method it always gives socket timeout exception.
    Do you have any idea about this weird situation?


  30. Georgian Micsa 5th June 2013 at 8:03 pm - Reply

    It seems to be only a SOAPUI problem, I could call the web service from a Java client.

  31. Niha 12th June 2013 at 4:32 pm - Reply

    This comment has been removed by the author.

  32. Dario 14th June 2013 at 3:42 pm - Reply

    Great work. Clear explanation.



  33. Unknown 8th July 2013 at 5:05 pm - Reply

    Would you please explain what type of Project is created and which eclipse. I am trying to use Eclipse 3.5.2. I can see Dynamic/Static/Web service project. I am new to Web Services and all, but know Java. I am having some trouble to select which project to do.

  34. Brian 9th July 2013 at 6:50 am - Reply

    Instead of creating a new project using an Eclipse template you'll need to import the Maven project. GO to File->Import->Maven->Existing Maven Projects and point it at the POM.

  35. Bala 11th July 2013 at 7:35 pm - Reply

    This comment has been removed by the author.

  36. Bala 11th July 2013 at 7:37 pm - Reply

    Excellent work with crystal clear explanations. Thanks for this wonderful work Brian!!.

  37. Ivan Evseev 19th July 2013 at 2:48 pm - Reply

    Great article!

  38. naryan 3rd August 2013 at 4:39 am - Reply

    How do you display/log the complete raw SOAP request/response from webservice client that is generated using axis2.

  39. George Trandafir 19th August 2013 at 3:53 pm - Reply

    I am using jaxb2 and facing the following error:
    org.xml.sax.SAXParseException; systemId: file:/C:/Users/gtrandafir/workspace_kepler/PATServer/src/main/webapp/schemas/HRISDetailsServiceOperations.xsd; lineNumber: 19; columnNumber: 45; src-resolve: Cannot resolve the name 'hris:HRIS' to a(n) 'type definition' component.
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:198)
    at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:134)
    at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:437)
    at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDHandler.reportSchemaErr(XSDHandler.java:4124)
    at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDHandler.reportSchemaError(XSDHandler.java:4107)
    at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDHandler.getGlobalDecl(XSDHandler.java:1730)
    at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDElementTraverser.traverseNamedElement(XSDElementTraverser.java:405)
    at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDElementTraverser.traverseLocal(XSDElementTraverser.java:194)
    at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDHandler.traverseLocalElements(XSDHandler.java:3580)
    at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDHandler.parseSchema(XSDHandler.java:622)
    at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaLoader.loadSchema(XMLSchemaLoader.java:588)
    at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaLoader.loadGrammar(XMLSchemaLoader.java:555)
    at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaLoader.loadGrammar(XMLSchemaLoader.java:521)
    at com.sun.org.apache.xerces.internal.jaxp.validation.XMLSchemaFactory.newSchema(XMLSchemaFactory.java:240)
    at com.sun.tools.xjc.reader.xmlschema.parser.SchemaConstraintChecker.check(SchemaConstraintChecker.java:101)
    at com.sun.tools.xjc.ModelLoader.loadXMLSchema(ModelLoader.java:357)
    at com.sun.tools.xjc.ModelLoader.load(ModelLoader.java:167)
    at com.sun.tools.xjc.ModelLoader.load(ModelLoader.java:113)
    at com.sun.tools.xjc.Driver.run(Driver.java:313)

    Any ideas, please?
    PS: i am using maven from CLI.

  40. Brian 20th August 2013 at 6:09 am - Reply

    Hi George.
    The first step is to validate your XSD document and make sure there are no issues. If you open the document in XMLSpy you can validate it by pressing F8. If there are issues, XMLSpy will highlight the point of failure which should make the problem easy to resolve.


  41. M Zaky 22nd August 2013 at 11:20 pm - Reply

    I could not build with maven:
    org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.codehaus.mojo:jaxb2-maven-plugin:1.4:xjc (default-cli) on project spring-webservices-sample: Could not process schema files in directory
    Notice that the schemas are located in : src/main/webapp/schemas
    Any idea?

  42. M Zaky 24th August 2013 at 11:49 am - Reply

    This comment has been removed by the author.

  43. M Zaky 24th August 2013 at 11:59 am - Reply

    Hi all,

    I resolved it, when I changed the version of the plugin to 1.5 and I put the schemas files in the right folder (as defined in the documentation of the plugin, http://mojo.codehaus.org/jaxb2-maven-plugin/xjc-mojo.html):

    I hope it will help!

    Kind regards

  44. npeducations 1st October 2013 at 5:01 am - Reply

    thaks for the valuable information which made me more helpful in my project work.

  45. Diego Herrera 21st October 2013 at 4:54 am - Reply

    I have the error I ws.server.EndpointNotFound. some solution?

    DEBUG: [oct-21 01:48:18,355] transport.http.WsdlDefinitionHandlerAdapter – Transforming [/endpoints] to [http://localhost:8080/SpringWebService01/endpoints]
    DEBUG: [oct-21 01:48:18,361] transport.http.MessageDispatcherServlet – Successfully completed request
    DEBUG: [oct-21 01:48:31,820] transport.http.WebServiceMessageReceiverHandlerAdapter – Accepting incoming [org.springframework.ws.transport.http.HttpServletConnection@e3d4e8] at [http://localhost:8080/SpringWebService01/endpoints]
    DEBUG: [oct-21 01:48:31,862] server.MessageTracing.received – Received request [SaajSoapMessage {http://com/company/webservices/accountservice}AccountDetailsRequest]
    DEBUG: [oct-21 01:48:31,893] endpoint.mapping.PayloadRootAnnotationMethodEndpointMapping – Looking up endpoint for [{http://com/company/webservices/accountservice}AccountDetailsRequest]
    DEBUG: [oct-21 01:48:31,893] soap.server.SoapMessageDispatcher – Endpoint mapping [org.springframework.ws.server.endpoint.mapping.PayloadRootAnnotationMethodEndpointMapping@1a954f8] has no mapping for request
    DEBUG: [oct-21 01:48:31,894] endpoint.mapping.SoapActionAnnotationMethodEndpointMapping – Looking up endpoint for []
    DEBUG: [oct-21 01:48:31,894] soap.server.SoapMessageDispatcher – Endpoint mapping [org.springframework.ws.soap.server.endpoint.mapping.SoapActionAnnotationMethodEndpointMapping@9770b] has no mapping for request
    WARN : [oct-21 01:48:31,894] ws.server.EndpointNotFound – No endpoint mapping found for [SaajSoapMessage {http://com/company/webservices/accountservice}AccountDetailsRequest]
    DEBUG: [oct-21 01:48:31,895] transport.http.MessageDispatcherServlet – Successfully completed request

  46. Michael McCabe 30th October 2013 at 1:24 pm - Reply

    Brian, this is the best tutorial I've ever seen on spring java WS. Keep up the good work!

  47. Anonymous 5th November 2013 at 9:10 pm - Reply

    Hey Brian. Thanks a million for the tutorial. Michaels statement (above) rings true for me too. I have followed your approach whilst building my own application. I am returning hardcoded data from the Account class.

    As an additional step, I am trying to add Hibernate to the project. The problem is, when I add the relevant annotations to the JAXB generated Account class, they get overwritten. Do you know what is the correct way to go about this?


  48. Anonymous 5th November 2013 at 9:14 pm - Reply

    Diego, I also had this problem. You need to make sure you have carefully typed the spring-config.xml as well as having matching variable names / paths in AccountServicesEndpoints.java. The problem is exactly as the logs state, the endpoint which you have specified cannot be found.

  49. Rat Net 23rd November 2013 at 10:59 am - Reply

    Hello All, I've no compile time error in my eclipse project but at runtime the application is not working and presented the following error logs:

    INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/config/spring-config.xml]
    ????? ??, ???? ?:??:?? ??????? org.springframework.web.context.ContextLoader initWebApplicationContext
    SEVERE: Context initialization failed
    org.springframework.beans.factory.BeanDefinitionStoreException: Unexpected exception parsing XML document from ServletContext resource [/WEB-INF/config/spring-config.xml]; nested exception is java.lang.NoClassDefFoundError: org/springframework/xml/transform/TransformerObjectSupport

  50. Gomathi T 24th November 2013 at 5:20 am - Reply

    Thanks for the tutorial. Its very clear for new learners of Spring WebServices Configuration. Thanks for the excellent one…

  51. raj 3rd December 2013 at 2:22 pm - Reply


    This tutorial is looking good but actually I am new in Spring and I have to create Spring web service. So can anybody help me to write from starting like how to create the spring project and how JAXB can be used to generate the classes from XSD. If anybody have details document please provide me .

  52. Swamy 4th December 2013 at 11:18 am - Reply

    thanks .As i am working on spring web services.It is useful for me.

  53. Divya Besant 26th December 2013 at 6:05 am - Reply

    Nice Blog contact for more info

  54. ROHIT JAIN 4th January 2014 at 12:31 pm - Reply

    Awesome Blog…..thanks!!!

  55. blue dream 10th February 2014 at 3:28 pm - Reply

    Perfect, Thanks!! This should be replaced by this: http://docs.spring.io/spring-ws/site/reference/html/tutorial.html

    Do you also have any Idea how to call this Web service from java script or Ajax or anything on a HTML???

  56. Rogério Reis Batista 7th March 2014 at 8:35 pm - Reply

    Very, very good. I liked so much. Now I could understand how spring ws works. Thank you for this tutorial.

  57. laffu 8th March 2014 at 9:10 pm - Reply

    very nice tutorial.

    one thing I noticed though is that .. in soapUI, you pass any account number, it responds with the 12345 details.

  58. Olive Arnold 3rd April 2014 at 11:09 am - Reply

    Graet post

    php development

  59. Rashmi Singh 19th May 2014 at 8:47 pm - Reply

    Hi Brian, Thanks for the useful post. I was able to get it to work. I had a question though. Can you provide some help on how to do the same using Gradle instead of Maven? Do you have a build.gradle corresponding to the pom.xml that would essentially help do the same build?

  60. Akif Khan 6th June 2014 at 11:57 am - Reply

    Hi Brian, This is really an awesome tutorial for beginners, could you please identify what are the possible jars required to run this project.

  61. Brian 6th June 2014 at 12:20 pm - Reply

    All required dependencies are defined in the POM.xml. When you run a Maven build these resources will be downloaded to your local Maven repository (if you don't already have them) and get added to your applications class path.

  62. Dunith Dhanushka 8th June 2014 at 7:06 am - Reply

    Well, this made my day. Very comprehensive tutorial indeed. Thanks for sharing!

  63. Shubham Goel 11th June 2014 at 10:17 pm - Reply

    Now this was one awesome tutorial for a complete spring WS beginner !!

  64. sluggo 19th June 2014 at 8:30 pm - Reply

    Took a bit to get the right XmlSchema jar downloaded (Use:

    But otherwise worked GREAT!!

  65. Santhosh Mamulla 25th June 2014 at 12:33 pm - Reply

    Hi Brian,
    It is best tutorial for beginners to understand Spring WS
    Thanks for this post.. 🙂

  66. Anbukarasi J 29th June 2014 at 11:21 am - Reply

    This comment has been removed by the author.

  67. Sophia Right 18th July 2014 at 9:01 am - Reply

    Great post. I Like to read your post. I gonna to bookmark your post. Thanks for sharing all links I am sure they are useful.

  68. Hosting Raja 5th August 2014 at 7:54 am - Reply

    This is an excellent blog because it has good volume of information, everything is described in the simplest manner and all information on this blog is genuine and real..best web hosting | web hosting sites

  69. George Celvi 9th August 2014 at 12:19 am - Reply

    I am trying to access the WebServiceContext within an operation and have ..
    public void setWebServiceContext(WebServiceContext c) {
    wsCtxt = c;
    added this code to the AccountServiceImpl class
    It always returns null…
    Is there a way to access the WebServiceContext?

  70. santosh raju 25th August 2014 at 10:02 am - Reply

    hi brain…can u please re-Commit the whole project..many packages are missing after checking out the project…great tutorial..thanks

  71. santosh raju 25th August 2014 at 11:07 am - Reply

    hi brian…can u please re-Commit the whole project..many packages are missing after checking out the project…great tutorial..thanks

  72. Rima 13th September 2014 at 7:11 pm - Reply

    Thanks Brian for a such wonderful blog.It helped me lot.

  73. Makky 15th September 2014 at 1:44 pm - Reply

    Its missing lots of things. You forgot to add wsdl4j and other deps.

  74. bala10 16th September 2014 at 4:55 am - Reply

    Hi Brain,
    Can you please brief a little on adding SOAP Header to the above web service example

  75. Makky 21st September 2014 at 8:58 am - Reply

    This is complicated. This can be done with Apache CXF easily…

    For full tutorial (WSDL, Server and Client) follow here


  76. mary jane 14th October 2014 at 2:52 am - Reply

    Hi Brian,

    I am doing a project both web app and web services in it. I put web app files into a package: com.motelming.j2ee.webapp. I put web services files into another package: com.motelming.j2ee.services. Now I tried to get the .wsdl file and failed. Here is the error message:


    2014-10-13 22:42:51 ERROR MessageDispatcherServlet:492 – Context initialization failed
    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'RoomDetailsService' defined in ServletContext resource [/WEB-INF/spring-config.xml]: Cannot create inner bean 'org.springframework.xml.xsd.commons.CommonsXsdSchemaCollection#76c99fd9' of type [org.springframework.xml.xsd.commons.CommonsXsdSchemaCollection] while setting bean property 'schemaCollection'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.xml.xsd.commons.CommonsXsdSchemaCollection#76c99fd9' defined in ServletContext resource [/WEB-INF/spring-config.xml]: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: org.apache.ws.commons.schema.XmlSchemaCollection.read(Lorg/xml/sax/InputSource;)Lorg/apache/ws/commons/schema/XmlSchema;

    Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.xml.xsd.commons.CommonsXsdSchemaCollection#76c99fd9' defined in ServletContext resource [/WEB-INF/spring-config.xml]: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: org.apache.ws.commons.schema.XmlSchemaCollection.read(Lorg/xml/sax/InputSource;)Lorg/apache/ws/commons/schema/XmlSchema;

    Caused by: java.lang.NoSuchMethodError: org.apache.ws.commons.schema.XmlSchemaCollection.read(Lorg/xml/sax/InputSource;)Lorg/apache/ws/commons/schema/XmlSchema;

    HTTP Status 404 – /com.motelming.j2ee.services/endpoints/RoomDetailsService.wsdl

    type Status report

    message /com.motelming.j2ee.services/endpoints/RoomDetailsService.wsdl

    description The requested resource is not available.

  77. Allan 31st October 2014 at 1:51 pm - Reply

    This comment has been removed by a blog administrator.

  78. Amit 5th November 2014 at 8:53 pm - Reply

    This comment has been removed by the author.

  79. Zoltan 25th November 2014 at 10:15 pm - Reply

    Hi Brian, great blog.
    Can you explain, how to add basic authentication to the service getAccountDetails ? (username, password)

  80. pedroj 28th December 2014 at 8:27 pm - Reply

    Great tutorial, thank you very much…..

  81. Bindu Bhavsar 30th December 2014 at 4:39 pm - Reply

    hi Brian,
    i tweaked the tutorial for my project. but, my wsdl that is generated doesnt have any messages or operations in it. so i cannot test in SOAPUI. am i missing a configuration?

  82. Deepu 4th January 2015 at 5:15 pm - Reply

    Hi Brian,
    As in the WSDL soap action is blank [soap:operation soapAction=""], Can you suggest , how to set it for multiple operations.

  83. Pooja 9th January 2015 at 9:47 pm - Reply

    Facing same issue.

  84. Pooja 9th January 2015 at 9:50 pm - Reply

    May I know how we can use spring-ws framework while working with multiple maven sub projects? I mean one for service having service implementations and other like web having XSDs and configuration files?

  85. Jack William 16th January 2015 at 6:13 am - Reply

    Yes i truly agree with Anshul and really wanna thank Brian for the post. Please keep sharing your knowledge with us!

    PHP website development in Mumbai

  86. Kathiresan Muthu 2nd February 2015 at 8:48 am - Reply

    Hi this is Kathiresan i am having 3 years of experience as a dot net developer and i am certified. i have knowledge on OOPS concepts in .NET but dont know indepth. After learning android will be enough to get a good career in IT with good package? and i crossed Android Training in Chennai website where someone please help me to identity the syllabus covers everything or not??


  87. amit kumar singh 4th February 2015 at 3:28 pm - Reply

    please suggest ways to use this

  88. syam kumar chatakondu 10th February 2015 at 5:11 pm - Reply

    Hi Brain, thanks for a such nice detailed explanation.
    I am facing the following error while deploying the war into jboss. please guide me

    nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/config/spring-config.xml]

  89. joyeeta datta 24th February 2015 at 5:39 pm - Reply

    Hello Brain, thanks for such a nice tutorial. I am facing the issue when I am trying to consume a webservice hosted on an https port. I am getting ssl related issues. Is there any option that I need to set to resolve this issue?
    I am able to consume the same webservice using axis 2 without any issues in my local system.

  90. Mohan Seth 24th May 2015 at 8:35 am - Reply

    The packages that are missing have to be generated using jaxb from xsd, follow this link

  91. Mohan Seth 24th May 2015 at 8:36 am - Reply

    This comment has been removed by the author.

  92. Quý Nguyễn 9th June 2015 at 6:40 am - Reply

    Brilliant Brian. This helps me get what I need to know quickly. Much more easier to understand than the Spring docs…

  93. SABRIN 22nd June 2015 at 3:13 am - Reply

    This comment has been removed by the author.

  94. SABRIN 22nd June 2015 at 3:13 am - Reply

    Hi Brian, Thanks for a brilliant tutorial, Could you please let us know how do we use the same sample with https port, and also need to know how to set the ClientIP address and timestamp in the request soap xml along with the existing account number where we pass as input.

    Any help on this will be much appreciated.


  95. jasmin dhamelia 25th June 2015 at 9:08 pm - Reply

    I was wondering how we can add header to soap request? anybody knows how to do it?

  96. Interface Planet 16th July 2015 at 2:02 pm - Reply

    This comment has been removed by the author.

  97. Adventurous 30th July 2015 at 5:28 pm - Reply

    How to access wsdl with "?wsdl" instead of ".wsdl"

  98. Jithin 20th August 2015 at 2:54 pm - Reply

    Impressive, I didn't had to do anything, other than to just download from github and run some maven thing and ready for deployment and consuming them…….

    I just wanted to know if you have a similar implementation for Web Service client using Spring Web Service templates and I don't want to generate the client stubs by myself.

  99. Nupur Dhawan 15th September 2015 at 7:02 pm - Reply

    Thanks for the article. Plz also give some theoretical details about Spring Web-services or a link if so for better understanding.

  100. Nupur Dhawan 15th September 2015 at 7:02 pm - Reply

    This comment has been removed by the author.

  101. Kristen Charlize Smith 3rd October 2015 at 12:18 am - Reply

    Great article. As a developer myself, I also do some wordpress service and I can say that this is one of the Java blogs I often read. Good stuff here. Keep it up!

  102. Ramana Vukoti 14th October 2015 at 6:39 am - Reply

    thanks Brians … helped alot
    is ther any other way to configure xml using <ws:dynamic-wsdl ….?? in springws-conifg.xml

  103. Amogh 9th February 2016 at 3:23 pm - Reply

    This comment has been removed by the author.

  104. Amogh 10th February 2016 at 3:12 am - Reply

    This comment has been removed by the author.

  105. Amogh 10th February 2016 at 3:12 am - Reply

    This comment has been removed by the author.

  106. Aditya 14th February 2016 at 10:46 am - Reply

    Trying this in 2016, it does not work out of the box. But it still does a great job of giving a direction to work with Spring WS. Thank you for this. It helped me.

  107. Antoni Isaias Cardenas Contreras 11th May 2016 at 11:02 pm - Reply

    It's posible do this.
    @PayloadRoot(localPart = "AccountDetailsRequest", namespace = TARGET_NAMESPACE)
    public @ResponsePayload String getAccountDetails(@RequestPayload String request)

    Use String in request and response

  108. Adam smith 29th July 2016 at 4:25 pm - Reply


  109. Roger Parkinson 7th August 2016 at 9:23 am - Reply

    This was a huge help, thanks.

  110. ramkomarapu 12th August 2016 at 6:16 am - Reply

    Hi Brain,

    I have a WSDL, need to build a SOAP based webservice. Please suggest the steps i need to follow in building the webservice.
    Thank you

  111. Brian 12th August 2016 at 6:17 am - Reply

    Follow the steps in this post 🙂

  112. Subhobroto Roy 12th August 2016 at 7:35 pm - Reply

    Thank you very much for this nice tutorial….I know you have posted one tutorial about how to create client for this SOAP web service using AXIS2, but it will be very much helpful if you can create client using WebServiceTemplate of Spring.Please post one article on that.

  113. Unknown 23rd October 2016 at 8:41 pm - Reply

    I too agree with others, one of the finest way of explaining SOAP web service and its consumption.

  114. Chetna 2nd November 2016 at 9:31 pm - Reply

    Hi Brian,

    I created a project as stated above but I do not know how to deploy this as mentioned in Deploying the Service section. Please sugest!

  115. Ramneek 21st March 2017 at 8:30 pm - Reply

    Great tutorial, thanks for sharing.

  116. upender rangu 20th April 2017 at 3:48 pm - Reply

    Thanks alot brain.this tutorial helped me a lot.

  117. Deepti Tunk 19th May 2017 at 7:12 pm - Reply

    Thank you so much Brain . This tutorial was easy to understand and implemement . Request you to provide a Spring WS Username Password Authentication Wss4j example

  118. Unknown 24th July 2017 at 7:15 am - Reply

    excellent tutorial

Leave A Comment