JAX-WS + Spring integration example

Here’s a guide to show you how to integrate Spring with JAX-WS, as mention in this link : http://jax-ws-commons.java.net/spring/. Upon finishing this tutorial, you will create a simple HelloWorld web service (JAX-WS), and DI a bean into the web service via Spring.

1. Project Folder

See the final project folder structure.

jaxws-spring-folder-structure

2. Project Dependencies

Use Maven to get all the library dependencies. The key to integrate Spring with JAX-WS is via jaxws-spring.jar.

File : pom.xml


<project xmlns="http://maven.apache.org/POM/4.0.0" 
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
  http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.mkyong</groupId>
  <artifactId>WebServicesExample</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>WebServicesExample Maven Webapp</name>
  <url>http://maven.apache.org</url>

  <repositories>
    <repository>
      <id>java.net</id>
      <url>http://download.java.net/maven/2</url>
    </repository>
  </repositories>
   
  <dependencies>

        <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>3.8.1</version>
                <scope>test</scope>
        </dependency>
	
	<!-- Spring framework --> 
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring</artifactId>
		<version>2.5.6</version>
	</dependency>
 
        <!-- JAX-WS --> 
	<dependency>
	  	<groupId>com.sun.xml.ws</groupId>
	        <artifactId>jaxws-rt</artifactId>
	        <version>2.2.3</version>
	</dependency>
  
 	<!-- Library from java.net, integrate Spring with JAX-WS --> 
	<dependency>
		<groupId>org.jvnet.jax-ws-commons.spring</groupId>
		<artifactId>jaxws-spring</artifactId>
		<version>1.8</version>
		<exclusions>
		  <exclusion>
           		<groupId>org.springframework</groupId>
      			<artifactId>spring-core</artifactId>
        	  </exclusion>
        	  <exclusion>
           		<groupId>org.springframework</groupId>
      			<artifactId>spring-context</artifactId>
        	  </exclusion>
        	  <exclusion>
           		<groupId>com.sun.xml.stream.buffer</groupId>
      			<artifactId>streambuffer</artifactId>
        	  </exclusion>
        	  <exclusion>
           		<groupId>org.jvnet.staxex</groupId>
      			<artifactId>stax-ex</artifactId>
        	  </exclusion>
		</exclusions>
	</dependency>
	
  </dependencies>
  <build>
    <finalName>web services</finalName>
    <plugins>
       <plugin>
           <groupId>org.apache.maven.plugins</groupId>
           <artifactId>maven-compiler-plugin</artifactId>
           <version>2.3.1</version>
           <configuration>
               <source>1.6</source>
               <target>1.6</target>
           </configuration>
       </plugin>
    </plugins>
  </build>
</project>
Note
The jaxws-spring’s pom.xml has a lot of unnecessary dependencies, you may need to exclude it via </exclusions> tag.

3. JAX-WS Hello World

A simple JAX-WS example, and dependency inject (DI) “HelloWorldBo” via Spring.

File : HelloWorldWS.java


package com.mkyong.ws;

import javax.jws.WebMethod;
import javax.jws.WebService;

import com.mkyong.bo.HelloWorldBo;

@WebService
public class HelloWorldWS{

	//DI via Spring
	HelloWorldBo helloWorldBo;

	@WebMethod(exclude=true)
	public void setHelloWorldBo(HelloWorldBo helloWorldBo) {
		this.helloWorldBo = helloWorldBo;
	}

	@WebMethod(operationName="getHelloWorld")
	public String getHelloWorld() {
		
		return helloWorldBo.getHelloWorld();
		
	}
 
}

4. Beans

Here’s the HelloWorldBo class, with a getHelloWorld() method to return a simple string.

File : HelloWorldBo.java


package com.mkyong.bo;

public interface HelloWorldBo{

	String getHelloWorld();
	
}

File : HelloWorldBoImpl.java


package com.mkyong.bo.impl;

import com.mkyong.bo.HelloWorldBo;

public class HelloWorldBoImpl implements HelloWorldBo{

	public String getHelloWorld(){
		return "JAX-WS + Spring!";
	}
	
}

5. Spring Beans Configuration

Spring beans configuration file to bind URL pattern “/hello” to “com.mkyong.ws.HelloWorldWS” web service class.

File : applicationContext.xml


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:ws="http://jax-ws.dev.java.net/spring/core"
       xmlns:wss="http://jax-ws.dev.java.net/spring/servlet"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
       http://jax-ws.dev.java.net/spring/core
        http://jax-ws.dev.java.net/spring/core.xsd
        http://jax-ws.dev.java.net/spring/servlet
        http://jax-ws.dev.java.net/spring/servlet.xsd"
>
 
    <wss:binding url="/hello">
        <wss:service>
            <ws:service bean="#helloWs"/>
        </wss:service>
    </wss:binding>

    <!-- Web service methods -->
    <bean id="helloWs" class="com.mkyong.ws.HelloWorldWS">
    	<property name="helloWorldBo" ref="HelloWorldBo" />
    </bean>
    
    <bean id="HelloWorldBo" class="com.mkyong.bo.impl.HelloWorldBoImpl" />
    
</beans>
Note
With this jaxws-spring integration mechanism, the sun-jaxws.xml file is no longer required.

6. web.xml

In web.xml, declares “com.sun.xml.ws.transport.http.servlet.WSSpringServlet“, and link it to “/hello“.


<web-app id="WebApp_ID" version="2.4" 
	xmlns="http://java.sun.com/xml/ns/j2ee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

	<display-name>Spring + JAX-WS</display-name>

	<servlet>
    	        <servlet-name>jaxws-servlet</servlet-name>
    	       <servlet-class>
    		          com.sun.xml.ws.transport.http.servlet.WSSpringServlet
    	        </servlet-class>
  	</servlet>
	
	<servlet-mapping>
                <servlet-name>jaxws-servlet</servlet-name>
                <url-pattern>/hello</url-pattern>
         </servlet-mapping>
 
         <!-- Register Spring Listener -->
  	<listener>
    	        <listener-class>
    		     org.springframework.web.context.ContextLoaderListener
    	        </listener-class>
  	</listener>
  	
</web-app>

7. Demo

Start the project, and access the deployed web service via URL “/hello“, for example http://localhost:8080/WebServicesExample/hello?wsdl

jaxws-spring-demo
Download it – JAX-WS-Spring-Integration-Example.zip (10KB)

Reference

  1. JAX-WS + Java Web Application Integration Example
  2. http://jax-ws-commons.java.net/spring/
  3. http://weblogs.java.net/blog/kohsuke/archive/2007/01/spring_support.html

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
bvn13
Guest
bvn13

Hello! Thank you for your article. But I still have a question. What setting makes the sun-jaxws.xml file as “no longer required”? Seems I did as you told, but I still have the error of missing this file.

dmm
Guest
dmm

it‘s code not work!!!!!

Abhishek
Guest
Abhishek

Very nice and simple tutorial, Anybody with minimal spring knowledge can go through and run this example to have very basic understanding of spring web services, Which can be further built up to the level one aspires, Kudos !! you’re really a saviour in wave of new technologies :)

Kotomi Ichinose
Guest
Kotomi Ichinose

How could i do this use java base config?I couldn’t find wws:binding info in java code.

Bishal ghimire
Guest
Bishal ghimire

DO we need to add any other configuration to make it work for Websphere application? I tried to deploy it creating war or ear; the application server didn’t recognize it.

Raja
Guest
Raja

Did you solve the issue while deploying to Websphere?

waheed
Guest
waheed

Hi,

I want to integrate Jax-ws with jsf1.2,share the web.xml

Guillermo Díaz S.
Guest
Guillermo Díaz S.

Mkyong, do you have a example where you use spring 4 annotation config?

Naman Gala
Guest
Naman Gala

Is this method supported by Spring 3.2.3 instead of mentioned 2.5.6 version?

Thanuja
Guest
Thanuja

Hi, I am unable to log soap request/response. I used SOAPHandler earlier, but it is not working with this implementation. Do you have any idea?

bss
Guest
bss

org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 1 in XML document from ServletContext resource [/WEB-INF/applicationContext.xml] is invalid; nested exception is org.xml.sax.SAXParseException: Premature end of file.

Krishna
Guest
Krishna

I am getting error can any body give me list jars for this projects that is require

Juan R
Guest
Juan R

Hi mkyong , I want to have several endpoints in this example and I don’t now how do that

trackback
JAVA – Como criar um WebService JAX-WS com SPRING 3 | iDeIAS

[…] Referencias mais completas: REF1 REF2 REF3 REF4 […]

trackback
JAVA – Criando um WebService com SPRING | iDeIAS

[…] Referencias mais completas: REF1 REF2 REF3 REF4 […]

mkyong
Guest
mkyong

Sorry, do you mean I should translate it to Chinese?

Hasto
Guest
Hasto

i found solving problem xsd from this : http://stackoverflow.com/questions/14741729/jax-ws-schema-http-jax-ws-dev-java-net-spring-servlet-xsd-not-able-to-be-found

or u can get my part code .xml this :

but i still have error, i cant access : http://localhost:8080/WebServicesExample/hello?wsdl
404 Not Found : Invalid Request
anyone can help me?

trackback
Spring – SOAP Web Service IntegrationCopyQuery CopyQuery | Question & Answer Tool for your Technical Queries,CopyQuery, ejjuit, query, copyquery, copyquery.com, android doubt, ios question, sql query, sqlite query, nodejsquery, dns query, update

[…] Have referred “http://www.mkyong.com/webservices/jax-ws/jax-ws-spring-integration-example/&#8221; link to make it work but no […]

JavaCoder
Guest
JavaCoder

How can I get the XSD (or schema) inline instead of it pointing to the URL?

Thanks in advance.

Uj
Guest
Uj

Hi,

I have downloaded the zip file and edited xsd locations as mentioned above but still I am getting org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 1 in XML document from ServletContext resource [/WEB-INF/applicationContext.xml] is invalid; nested exception is org.xml.sax.SAXParseException; systemId: http://jax-ws.java.net/spring/servlet.xsd; lineNumber: 1; columnNumber: 1; Premature end of file when I run on the tomcat server

cg
Guest
cg
This is the 5th or 6th example/tutorial I am following from your side. In most of these you follow a pattern in which in the first step you show the directory structure. It seems from the eclipse ide. However, you dont mention which option you took to create the project. I mean particularly for this example: was this project created as “dynamic web project” or “web service” or “maven” or something else. I normally try to create everything manually if not specified. As in this example, i created folders and then files in it. I tried to build by mvn… Read more »
KingDevil
Guest
KingDevil

I followed the guide and run on client successful. But when I used Android device to call the webservice. I never put param to method on webservice. It’s always null value? Can you help me fix it?

Yingjie
Guest
Yingjie

Compile and package successful; and after deploy on my tomcat, the wsdl file cannot be displayed. http://localhost:8080/WebServicesExample/hello?wsdl

BTW, the http://jax-ws.dev.java.net/spring/core http://jax-ws.java.net/spring/core.xsd http://jax-ws.dev.java.net/spring/servlet http://jax-ws.java.net/spring/servlet.xsd” have already been modified.b

Could you please tell me how could you fix it?

Thank you!

Steve
Guest
Steve

Hi there, thanks for the awesome tutorial!!

I am trying to print the request xml sent and the response recived from the Webservice on to my log and am following the instructions give here: http://static.springsource.org/spring-ws/site/reference/html/common.html#logging

However, despite many tries, I have had no luck in printing the xml to the logs. Any ideas?

Jatin Sharma
Guest
Jatin Sharma

Very Useful.

Ionut Craciun
Guest
Ionut Craciun
Hi guys, It seems that cannot be deployed in Tomcat 6, I get the following error: 10.06.2013 16:15:44 org.springframework.context.support.AbstractApplicationContext prepareRefresh INFO: Refreshing org.springframework.web.context.support.XmlWebApplicationContext@7461373f: display name [Root WebApplic ationContext]; startup date [Mon Jun 10 16:15:44 EEST 2013]; root of context hierarchy 10.06.2013 16:15:44 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/applicationContext.xml] 10.06.2013 16:15:45 org.springframework.web.context.ContextLoader initWebApplicationContext SEVERE: Context initialization failed org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 1 in XML document from ServletContext resour ce [/WEB-INF/applicationContext.xml] is invalid; nested exception is org.xml.sax.SAXParseException: Premature end of fil e. at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.j ava:404) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.jav a:342) at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.jav a:310) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefini tionReader.java:143) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefini tionReader.java:178) at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefini… Read more »
Ionut Craciun
Guest
Ionut Craciun

This is the WEB-INF/contextApplication.xml file:

Yasser
Guest
Yasser

Are you sure that you’ve mentioned all dependencies?! I created exact same small project but it says:

java.lang.ClassCastException: Cannot cast com.sun.xml.ws.security.impl.policy.SecurityPolicyValidator to com.sun.xml.ws.policy.spi.PolicyAssertionValidator
at java.lang.Class.cast(Class.java:3005)
at com.sun.xml.ws.policy.privateutil.ServiceFinder$LazyIterator.next(ServiceFinder.java:382)
at com.sun.xml.ws.policy.privateutil.ServiceFinder.toArray(ServiceFinder.java:232)
at com.sun.xml.ws.policy.privateutil.PolicyUtils$ServiceProvider.load(PolicyUtils.java:455)
at com.sun.xml.ws.policy.AssertionValidationProcessor.(AssertionValidationProcessor.java:85)
at com.sun.xml.ws.api.policy.ValidationProcessor.(ValidationProcessor.java:73)
at com.sun.xml.ws.api.policy.ValidationProcessor.getInstance(ValidationProcessor.java:83)
at com.sun.xml.ws.policy.jaxws.DefaultPolicyResolver.validateServerPolicyMap(DefaultPolicyResolver.java:88)
at com.sun.xml.ws.policy.jaxws.DefaultPolicyResolver.resolve(DefaultPolicyResolver.java:69)
at com.sun.xml.ws.policy.jaxws.PolicyWSDLParserExtension.postFinished(PolicyWSDLParserExtension.java:970)
at com.sun.xml.ws.wsdl.parser.DelegatingParserExtension.postFinished(DelegatingParserExtension.java:191)
at com.sun.xml.ws.wsdl.parser.WSDLParserExtensionFacade.postFinished(WSDLParserExtensionFacade.java:338)
at com.sun.xml.ws.wsdl.parser.RuntimeWSDLParser.parse(RuntimeWSDLParser.java:338)
at com.sun.xml.ws.server.EndpointFactory.getWSDLPort(EndpointFactory.java:645)
at com.sun.xml.ws.server.EndpointFactory.create(EndpointFactory.java:280)
at com.sun.xml.ws.server.EndpointFactory.createEndpoint(EndpointFactory.java:147)
at com.sun.xml.ws.api.server.WSEndpoint.create(WSEndpoint.java:574)
at com.sun.xml.ws.api.server.WSEndpoint.create(WSEndpoint.java:557)
at org.jvnet.jax_ws_commons.spring.SpringService.getObject(SpringService.java:333)
at org.jvnet.jax_ws_commons.spring.SpringService.getObject(SpringService.java:45)
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:142)
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.getObjectFromFactoryBean(FactoryBeanRegistrySupport.java:109)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:274)
at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:125)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1325)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1086)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)
at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:276)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:197)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3827)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4334)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:791)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:771)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:525)
at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:920)
at org.apache.catalina.startup.HostConfig.deployDirectories(HostConfig.java:883)
at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:492)
at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1138)
at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:311)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:719)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
at org.apache.catalina.core.StandardService.start(StandardService.java:516)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
at org.apache.catalina.startup.Catalina.start(Catalina.java:566)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)

It seems it needs webservices-rt.jat but after that it again says another error!!! :((

Giuseppe Annunziata
Guest
Giuseppe Annunziata

I’d like to warning about URLs for schema in spring configuration.
These now are:
http://jax-ws.java.net/spring/servlet.xsd
and
http://jax-ws.java.net/spring/core.xsd
(but namespace is still http://jax-ws.dev.java.net/spring/core and
http://jax-ws.dev.java.net/spring/servlet)

Amit
Guest
Amit

Hi,

I tried to compile but getting error in spring config file for wss binding :

Error :

Multiple annotations found at this line:
– schema_reference.4: Failed to read schema document ‘http://jax-ws.dev.java.net/spring/servlet.xsd’, because 1) could not
find the document; 2) the document could not be read; 3) the root element of the document is not .
– cvc-complex-type.2.4.c: The matching wildcard is strict, but no declaration can be found for element ‘wss:binding’.

michaeljoi
Guest
michaeljoi

I don’t know if this is a bug or not.

http://localhost:8080/WebServicesExample/hello?wsdl

Won’t give out the result as mentioned. I have to modify the pom.xml to be like this:
WebServicesExample

Or else it just won’t find the wsdl.

Yingjie
Guest
Yingjie

Hi michaeljoi,

I met the problem as you met. Compile and package successful; and after deploy on my tomcat, the wsdl file cannot be displayed. Could you please tell me how could you fix it?

Thank you!

Pradip Bhatt
Guest
Pradip Bhatt

Hi sir…
I am created different modules using Struts2 + Spring3.0 + Hibernate – JPA. Now my question is that How can I connect each independent module using web Service especially Spring Web Service.

Can Any one is helping me on this???

Thankssssssssss in Advance.

Gurditta
Guest
Gurditta

How would i create client to call this web service.?

thanks

veerareddy
Guest
veerareddy

Here webservices application is created, ok but you create client application, by using the SOAP aplication. ps cal to this number 09654457708.

Sumit Pal Singh
Guest
Sumit Pal Singh

Me too looking for the same…..anyone please answer…..I found a dummy client but am unable to call the getHelloWorld() method from it. Here is the dummy client:-

public class HelloWorldClient{

public static void main(String[] args) throws Exception {

URL url = new URL(“http://localhost:9080/test/hello?wsdl”);

QName qname = new QName(“http://ws.mkyong.com/”, “HelloWorldWSService”);

Service service = Service.create(url, qname);

}

}