Sunday, December 26, 2010

Spring WS 2 and Spring 3 MVC Integration Tutorial

In this tutorial we will integrate Spring WS 2 and Spring 3 MVC. We will develop a Spring WS web service that follows a Contract-First development. We will also take advantage of the latest Spring WS 2.0.0 RC2 features and use marshalling techniques to efficiently manipulate XML requests. We will use Spring 3 MVC to display our list of subscribers. It's highly recommended to read first the Spring WS: A Tutorial Using the Latest 2.0.0 RC2 Build because that's the foundation of this tutorial.

What is Spring Web Services (WS)?
Spring Web Services (Spring-WS) is a product of the Spring community focused on creating document-driven Web services. Spring Web Services aims to facilitate contract-first SOAP service development, allowing for the creation of flexible web services using one of the many ways to manipulate XML payloads. The product is based on Spring itself, which means you can use the Spring concepts such as dependency injection as an integral part of your Web service.

Source: Spring WS Reference 2.0

What is Contract-First development?
When creating Web services, there are two development styles: Contract Last and Contract First. When using a contract-last approach, you start with the Java code, and let the Web service contract (WSDL, see sidebar) be generated from that. When using contract-first, you start with the WSDL contract, and use Java to implement said contract.

Source: Spring WS Reference 2.0
For an in-depth look of Spring WS, I suggest my readers to visit the Spring WS Reference 2.0 and the Spring WS API 2.0.0.RC2

We begin by defining our requirements. We have a magazine business. Our business partner has clients that needs to subscribe with our magazine. To expose this feature, we decided to use a web service. Our contract is that the clients will send the following information:
subscription code
Our web service will send a reply if the subscription is successful or not. The reply will contain the following elements:
status code
Since all web services are ultimately XML message, we need to define the format of our messages. We will create an XSD file. If you're not familiar with XSD, please see the excellent XSD tutorial XML Schema Tutorial.

Here's our XSD document:


This XSD is comprised of simple and complex element types. Each simple element has been assigned with restriction. In this way we can filter data even before it comes to our service. It's also a good way to validate XML data. Spring WS will handle the validation based on these restrictions.

When the client sends a request, we receive an XML document. Using Java's object-oriented approach and XML approach is not really convenient when manipulating information. Therefore we will use marshalling techniques to map the XML document with a corresponding Java object.

First let's see the actual XML document that is sent to us by the client:

Take note that this XML format is not arbitrary! The client has to honor the format that we declared in the XSD document.

Let's map this document to a SubscriptionRequest class:


For every request sent by the client, we send a response. We declare a SubscriptionResponse object:

Our marshaller will automatically convert this class into an XML document. If you look at the XSD file, we have declared a subscriptionResponse element.

This has been declared so that the client who is reading our WSDL will see what kind of response he will receive. Hence, the Contract-First development.

When the client receives a response, this is what he actually gets:

Our class has been automatically converted to XML.

To convert Java objects to XML and vice-versa we use Castor as our marshaller/unmarshaller implementation. For more info about Castor, check the reference guide Castor XML Mapping. There are other marshallers available, such as JAXB and JiBX. Check the Spring WS Reference Guide Chapter 8. Marshalling XML using O/X Mapper for more info.

To use Castor we need to declare a mapping file:


We're done with our contract. We now start the actual development!

The programming model of Spring WS 2 is similar with the programming model of Spring 3 MVC. Keep that in mind. In Spring MVC, to declare a controller, we mark the name of the class with @Controller and @RequestMapping. For example:

In Spring WS, we have a corresponding controller as well. Actually, it's called an endpoint. To declare an endpoint, we mark it with @Endpoint. For example:

In Spring MVC, to expose a method for a particular request, we add the @RequestMapping annotation and the associated URI template value and the type of method. For example:

In Spring WS, to expose a method for a particular service request, we add the @PayloadRoot annotation and the associated localPart and namespace values. For example:

The method is also annotated with @ResponsePayload, indicating that the return value ( SubscriptionResponse) is used as the payload of the response message. The method takes a SubscriptionRequest as a parameter, annotated with @RequestPayload. This means that the payload of the message is passed on this method as a DOM element. If you have omitted these two annotations, you will encounter a "java.lang.IllegalStateException: No adapter for endpoint".

Let's now declare our SubscriptionEndpoint class:


This endpoint has one method named processSubscription. It takes a SubscriptionRequest and delegates the processing to a SubscriptionService. If the subscription is successful a SUCCESS response is sent. If it failed, a FAILURE response is sent.

Here's the SubscriptionService:


We're done with the Spring WS part. We now start the Spring MVC development.

What we're adding here are just basically a single controller and single JSP file to display our subscribers. Here's a screenshot of our subscribers list:

Here's the controller:


This controller declares a single mapping:
This mapping delegates the call to the SubscriptionService. This is the same service that's utilized by Spring WS earlier!

Here's the JSP file:

We're done will all our classes. What's left are the XML configurations. We start by declaring the web.xml file:


All request are handled by Spring MVC's DispatcherServlet. In a stand-alone Spring WS, we use the MessageDispatcherServlet instead. But since we're now integrating both, we need a way to resolve our dispatchers hierarchy.
As an alternative to the MessageDispatcherServlet, you can wire up a MessageDispatcher in a standard, Spring-Web MVC DispatcherServlet. By default, the DispatcherServlet can only delegate to Controllers, but we can instruct it to delegate to a MessageDispatcher by adding a WebServiceMessageReceiverHandlerAdapter to the servlet's web application context:

Spring WS 2 Reference 5.3.2. Wiring up Spring-WS in a DispatcherServlet
I suggest to read the Spring WS 2 reference for a thorough description of this integration.

If you examine carefully the servlet element, we've declared an init-param. This is required to dynamically convert WSDLs regardless where you deploy it. There's no need to manually set the URL of your WSDL anymore, though you still can.

In the web.xml we declared a servlet-name spring. By convention, we must declare a spring-servlet.xml as well.


By convention, we must declare an applicationContext.xml as well.


These beans activate Spring's annotation support for Spring 3 MVC. At the bottom portion we import an external configuration file spring-ws.xml. This contains all the Spring WS specific configuration. In a normal Spring project, it's typical to have multiple XML configs. To lessen the XML hell experience, it's advisable we group related configurations in their owned XML file.

Here's spring-ws.xml:


This configuration uses the latest Spring WS 2.0.0 RC2 features (unlike if you're still using 1.5.9).

What's new with Spring WS 2.0.0 RC2?
The most important new feature in this release is the update of the Spring-WS XML namespace, which now contains <sws:annotation-driven/> and <sws:interceptors/> elements (similar to the Spring-MVC namespace), and <sws:static-wsdl/> and <sws:dynamic-wsdl/> for exporting your WSDLs.

Source: SpringSource Forum: Spring Web Services 2.0.0 RC2 released
It's worth mentioning in the spring-ws.xml, we're using a pluggable endpoint adapter
and a marshalling method processor
If you visit some of the popular Spring WS tutorials, they still use the old GenericMarshallingMethodEndpointAdapter. However, this is already deprecated in favor of a pluggable adapter.
Class GenericMarshallingMethodEndpointAdapter

Deprecated. as of Spring Web Services 2.0, in favor of DefaultMethodEndpointAdapter and MarshallingPayloadMethodProcessor.

See Spring WS API 2.0.0 GenericMarshallingMethodEndpointAdapter
That concludes our Spring WS development. We've managed to setup a simple Spring 3 WS application using the latest Spring WS 2.0.0.RC2 build. We've utilized the latest annotation features. We've also leveraged Spring 3 MVC's programming model.

To test the application, you will need to deploy it in a server, like Tomcat. For the client, unless you know how to develop a Web Service client, I advise my readers to use Soap UI for testing. They have a free version at It's also one of the recommended tools at the official Spring Web Services site at

Here's a sample screenshot using SOAP UI to test the application:

To access the service endpoint, use the following URL:
To access the WSDL, use the following URL (you can use Firefox to check this out):
To access the subscribers page, use the following URL:
The best way to learn further is to try the actual application.

Download the project
You can access the project site at Google's Project Hosting at

You can download the project as a Maven build. Look for the in the Download sections.

You can run the project directly using an embedded server via Maven.
For Tomcat: mvn tomcat:run
For Jetty: mvn jetty:run

If you want to learn more about Spring MVC and integration with other technologies, feel free to read my other tutorials in the Tutorials section.
StumpleUpon DiggIt! Blinklist Yahoo Furl Technorati Simpy Spurl Reddit Google I'm reading: Spring WS 2 and Spring 3 MVC Integration Tutorial ~ Twitter FaceBook

Subscribe by reader Subscribe by email Share


  1. Thanks for this excellent tutorial !

  2. @Jose, thanks for comment. You might want to check the spring-ws-si project in the Spring Integration 2: Integrating a JDBC and WS System tuorial. It uses JAXB instead of Castor for marshalling. I'm planning to make a guide for it. But bassically it's the same idea

  3. I really have to say, that your tutorial is SUPERB!
    All the other tutorials on spring webservices don't compare to yours, you explain exactly what is needed to explain, thank you :)

  4. @Anonymous, thank for the comment :) I appreciate it

  5. Good post, facing the same issue.

    No adapter for endpoint

    Is your endpoint annotated with @Endpoint, or does it implement a supported interface like MessageHandler or PayloadEndpoint?

  6. Great Tutorial!
    I have tried to adapt it to run in Spring Roo. I get the WSDL, but once I post to the URL I get 404.

    Do you know if there any reason for this?

  7. very useful tutorial!

  8. Thanks for the tutorial.

    I have created all and I get an exception.
    Could you help me please?

  9. @Anonymous, this is a common issue with Spring WS. In my experience it could mean you're missing the @Endpoint annotation or the @RequestPayload annotation in your method arguments

  10. Really gud tutorial

  11. @krams - Thanks so much for sharing this tutorial. It is very clear and I have attempted to follow your steps to add MVC to an existing SpringWS service to allow a more simple method to monitor the health of the service. I had little to change to integrate MVC, but the Listener fails quietly:

    Apr 27, 2012 4:28:12 PM org.apache.catalina.core.StandardContext start
    SEVERE: Error listenerStart
    Apr 27, 2012 4:28:12 PM org.apache.catalina.core.StandardContext start
    SEVERE: Context [/BlahService] startup failed due to previous errors

    I have tweaked my logging but find no more to point to the issue. Woudl you have a recommendation on how to debug this?

  12. Hey,
    I launched your source code and noticed what generated WSDL has empty soapAction :(
    I tried to access services using SoapUI, but cannot figure out the URL for the action. Tried all the possible URLs including the obvious http://localhost:8080/krams/ws/subscriptionRequest/ but all I get is 404.

    Any ideas how to add soapAction to WSDL ? also figuring out the URL of the action would be great ?

    By the way the URLs you provided at the end of your post are wrong, for example your WSDL is accessible at http://localhost:8080/krams/ws/subscription.wsdl (exclude the "spring-ws" part).

  13. Simply superb!!
    just the kind of tutorial I am looking for.

    Keep posting such stuff.

  14. It works for me in Eclipse STS, thanks a lot for the great tutorial.
    Now I want to use my own location instead of But it does not resolve in the browser, so how can we know what to place there?

  15. Hi,
    I can access wsdl file but cannot access endpoint that has
    http://localhost:8080/spring-ws/krams/ws url. And get HTTP-404 error.

  16. Krams Your tutorial is awsome ! However i have a question, how i can add subscribers? under which address?

  17. Hi Kram.. how should i import this project into eclipse that i can get working copy..

    thanks in advance...

  18. Sir this error comes while running the project ::: Error occurred during deployment: Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'messageDispatcher' defined in ServletContext resource [/WEB-INF/mvc-ws-integration.xml]: Cannot resolve reference to bean 'defaultMethodEndpointAdapter' while setting bean property 'endpointAdapters' with key [0]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'defaultMethodEndpointAdapter' defined in ServletContext resource [/WEB-INF/spring-ws.xml]: Initialization of bean failed; nested exception is java.lang.NoClassDefFoundError: org/exolab/castor/xml/XMLException. Please see server.log for more details.

  19. Sres:
    The tutorial is very buene but I have the drawback that return a list, if it is eaten with soapUI or from the same JAVA if it returns the list but when consumed from. NET returns null, eye single to the list of other types of variable type I have problem or is that springws and beaver-mapping is not compatible with. NET:

    Code castor-mapping:

    Code XSD:

  20. Thank you thank you thank you thank you.

  21. Really fantastic.

  22. Thank you! Great tutorial!

  23. Hi Krams - I'd like to seek a help from you for this code.
    When I run on browser for
    http://localhost:8080/spring-ws/krams/ws - I don't see any output.

    http://localhost:8080/spring-ws/krams/main/subscribers - I only see blank data with header
    Id Name Email

  24. I have read your blog its very attractive and impressive. I like it your blog.

    Spring online training Spring online training Spring Hibernate online training Spring Hibernate online training Java online training

    spring training in chennai spring hibernate training in chennai

  25. This post is a helpful overview of the particular topic and very actionable. Interesting approach!
    steel spring in india

  26. Thanks for sharing this information and keep updating us. This is informatics and really useful to me.

    Best Industrial Training in Noida
    Best Industrial Training in Noida

  27. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.

    core java training in Electronic City

    Hibernate Training in electronic city

    spring training in electronic city

    java j2ee training in electronic city

  28. The effectiveness of IEEE Project Domains depends very much on the situation in which they are applied. In order to further improve IEEE Final Year Project Domains practices we need to explicitly describe and utilise our knowledge about software domains of software engineering Final Year Project Domains for CSE technologies. This paper suggests a modelling formalism for supporting systematic reuse of software engineering technologies during planning of software projects and improvement programmes in Project Centers in Chennai for CSE.

    Spring Framework has already made serious inroads as an integrated technology stack for building user-facing applications. Spring Framework Corporate TRaining the authors explore the idea of using Java in Big Data platforms.
    Specifically, Spring Framework provides various tasks are geared around preparing data for further analysis and visualization. Spring Training in Chennai

  29. Suggest good information in this message, click here.

  30. excellent post, very informative. I wonder why the other experts of this sector don’t notice this. You should continue your writing. I am confident, you have a huge readers’ base already!

  31. Wonderful post however , I was wanting to know if you could write a litte more on this subject? I’d be very grateful if you could elaborate a little bit further. Bless you! 카지노

  32. It is in point of fact a nice and helpful piece of info. I’m happy that you shared this helpful info with us. Please stay us up to date like this. Thank you for sharing. 토토사이트

  33. 카지노사이트 I love your blog.. very nice colors & theme. Did you create this website yourself
    or did you hire someone to do it for you? Plz reply as I'm
    looking to create my own blog and would like to find out where u got this from.
    thanks a lot

  34. 바카라사이트 It’s really a great and helpful piece of info. I’m glad that you just shared this useful information with us. Please keep us up to date like this. Thank you for sharing.

  35. 토토사이트 I found this to be interesting. Exciting to read your honest thought.

  36. 스포츠토토 Thanks for sharing excellent informations. Your web-site is very cool. I’m impressed by the details that you have on this site. It reveals how nicely you understand this subject. Bookmarked this web page, will come back for more articles. You, my pal, ROCK! I found simply the information I already searched all over the place and simply couldn’t come across. What a great web-site.

  37. I'm so happy to finally find a post with what I want. casino You have inspired me a lot. If you are satisfied, please visit my website and leave your feedback.

  38. That is a great tip particularly to those new to the blogosphere.
    Simple but very accurate info? Thank you for sharing this one.
    A must read post!
    Appreciating the hard work you put into your site and detailed information you present.
    Wonderful read!

  39. We absolutely love your blog and find almost all of your post’s to be just what I’m looking for.
    Simple but very accurate info? Thank you for sharing this one. A must read post!
    Appreciating the hard work you put into your site and detailed information you present.
    Wonderful read! I want to write like you. I hope you can read my post and let me know what to modify.
    My writing is in I would like you to visit my blog.