This guide walks you through the process of creating a SOAP-based web service server with Spring.

What You Will build

You will build a server that exposes data from various European countries by using a WSDL-based SOAP web service.

To simplify the example, you will use hardcoded data for the United Kingdom, Spain, and Poland.

What You Need

How to complete this guide

Like most Spring Getting Started guides, you can start from scratch and complete each step or you can bypass basic setup steps that are already familiar to you. Either way, you end up with working code.

To start from scratch, move on to Starting with Spring Initializr.

To skip the basics, do the following:

When you finish, you can check your results against the code in gs-soap-service/complete.

Starting with Spring Initializr

For all Spring applications, you should start with the Spring Initializr. The Initializr offers a fast way to pull in all the dependencies you need for an application and does a lot of the set up for you. This example needs the Spring Web and Spring Web Services dependencies.

You can get a Maven build file with the necessary dependencies directly from the Spring Initializr. The following listing shows the pom.xml file that is created when you choose Maven:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="" xmlns:xsi=""
		<relativePath/> <!-- lookup parent from repository -->
	<description>Demo project for Spring Boot</description>




You can get a Gradle build file with the necessary dependencies directly from the Spring Initializr. The following listing shows the build.gradle file that is created when you choose Gradle:

plugins {
	id 'org.springframework.boot' version '2.4.2'
	id 'io.spring.dependency-management' version '1.0.11.RELEASE'
	id 'java'

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-web'
	implementation 'org.springframework.boot:spring-boot-starter-web-services'

test {
Both the pom.xml and build.gradle files show additional build information, which you will add in the next step.

Add the Spring-WS dependency

The project needs to include spring-ws-core and wsdl4j as dependencies in your build file.

The following example shows the changes you need to make to the pom.xml file if you use Maven:


The following example shows the changes you need to make to the build.gradle file if you use Gradle:

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-web'
	implementation 'org.springframework.boot:spring-boot-starter-web-services'
    implementation 'wsdl4j:wsdl4j'

Create an XML Schema to Define the Domain

The web service domain is defined in an XML schema file (XSD) that Spring-WS will automatically export as a WSDL.

Create an XSD file with operations to return a country’s name, population, capital, and currency. The following listing (from src/main/resources/countries.xsd) shows the necessary XSD file:

<xs:schema xmlns:xs="" xmlns:tns=""
           targetNamespace="" elementFormDefault="qualified">

    <xs:element name="getCountryRequest">
                <xs:element name="name" type="xs:string"/>

    <xs:element name="getCountryResponse">
                <xs:element name="country" type="tns:country"/>

    <xs:complexType name="country">
            <xs:element name="name" type="xs:string"/>
            <xs:element name="population" type="xs:int"/>
            <xs:element name="capital" type="xs:string"/>
            <xs:element name="currency" type="tns:currency"/>

    <xs:simpleType name="currency">
        <xs:restriction base="xs:string">
            <xs:enumeration value="GBP"/>
            <xs:enumeration value="EUR"/>
            <xs:enumeration value="PLN"/>

Generate Domain Classes Based on an XML Schema

The next step is to generate Java classes from the XSD file. The right approach is to do this automatically during build time by using a Maven or Gradle plugin.

The following listing shows the necessary plugin configuration for Maven:


Generated classes are placed in the target/generated-sources/jaxb/ directory.

To do the same with Gradle, you first need to configure JAXB in your build file, as the following listing shows:

configurations {

bootJar {
    archiveBaseName = 'gs-producing-web-service'
    archiveVersion =  '0.1.0'
The build files have tag and end comments. These tags make it easier to extract bits of it into this guide for a more detailed explanation. You do not need these comments in your own build file.

The next step is to add the genJaxb task, which Gradle uses to generate Java classes. We need to configure gradle to find these generated Java classes in build/generated-sources/jaxb and add genJaxb as a dependency of compileJava task. The following listing shows the necessary addition:

sourceSets {
    main {
        java {
            srcDir 'src/main/java'
            srcDir 'build/generated-sources/jaxb'

task genJaxb {
    ext.sourcesDir = "${buildDir}/generated-sources/jaxb"
    ext.schema = "src/main/resources/countries.xsd"

    outputs.dir sourcesDir

    doLast() {
        project.ant {
            taskdef name: "xjc", classname: "",
                    classpath: configurations.jaxb.asPath
            mkdir(dir: sourcesDir)

            xjc(destdir: sourcesDir, schema: schema) {
                arg(value: "-wsdl")
                produces(dir: sourcesDir, includes: "**/*.java")

compileJava.dependsOn genJaxb

Because Gradle does not have a JAXB plugin (yet), it involves an Ant task, which makes it a bit more complex than in Maven.

In both cases, the JAXB domain object generation process has been wired into the build tool’s lifecycle, so there are no extra steps to run.

Create Country Repository

In order to provide data to the web service, create a country repository. In this guide, you create a dummy country repository implementation with hardcoded data. The following listing (from src/main/java/com/example/producingwebservice/ shows how to do so:

package com.example.producingwebservice;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

import io.spring.guides.gs_producing_web_service.Country;
import io.spring.guides.gs_producing_web_service.Currency;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

public class CountryRepository {
	private static final Map<String, Country> countries = new HashMap<>();

	public void initData() {
		Country spain = new Country();

		countries.put(spain.getName(), spain);

		Country poland = new Country();

		countries.put(poland.getName(), poland);

		Country uk = new Country();
		uk.setName("United Kingdom");

		countries.put(uk.getName(), uk);

	public Country findCountry(String name) {
		Assert.notNull(name, "The country's name must not be null");
		return countries.get(name);

Create Country Service Endpoint

To create a service endpoint, you need only a POJO with a few Spring WS annotations to handle the incoming SOAP requests. The following listing (from src/main/java/com/example/producingwebservice/ shows such a class:

package com.example.producingwebservice;

import org.springframework.beans.factory.annotation.Autowired;

import io.spring.guides.gs_producing_web_service.GetCountryRequest;
import io.spring.guides.gs_producing_web_service.GetCountryResponse;

public class CountryEndpoint {
	private static final String NAMESPACE_URI = "";

	private CountryRepository countryRepository;

	public CountryEndpoint(CountryRepository countryRepository) {
		this.countryRepository = countryRepository;

	@PayloadRoot(namespace = NAMESPACE_URI, localPart = "getCountryRequest")
	public GetCountryResponse getCountry(@RequestPayload GetCountryRequest request) {
		GetCountryResponse response = new GetCountryResponse();

		return response;

The @Endpoint annotation registers the class with Spring WS as a potential candidate for processing incoming SOAP messages.

The @PayloadRoot annotation is then used by Spring WS to pick the handler method, based on the message’s namespace and localPart.

The @RequestPayload annotation indicates that the incoming message will be mapped to the method’s request parameter.

The @ResponsePayload annotation makes Spring WS map the returned value to the response payload.

In all of these chunks of code, the io.spring.guides classes will report compile-time errors in your IDE unless you have run the task to generate the domain classes based on the WSDL.

Configure Web Service Beans

Create a new class with Spring WS-related beans configuration, as the following listing (from src/main/java/com/example/producingwebservice/ shows:

package com.example.producingwebservice;

import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.xml.xsd.SimpleXsdSchema;
import org.springframework.xml.xsd.XsdSchema;

public class WebServiceConfig extends WsConfigurerAdapter {
	public ServletRegistrationBean<MessageDispatcherServlet> messageDispatcherServlet(ApplicationContext applicationContext) {
		MessageDispatcherServlet servlet = new MessageDispatcherServlet();
		return new ServletRegistrationBean<>(servlet, "/ws/*");

	@Bean(name = "countries")
	public DefaultWsdl11Definition defaultWsdl11Definition(XsdSchema countriesSchema) {
		DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition();
		return wsdl11Definition;

	public XsdSchema countriesSchema() {
		return new SimpleXsdSchema(new ClassPathResource("countries.xsd"));
You need to specify bean names for MessageDispatcherServlet and DefaultWsdl11Definition. Bean names determine the URL under which the web service and the generated WSDL file are available. In this case, the WSDL will be available under http://<host>:<port>/ws/countries.wsdl.

This configuration also uses the WSDL location servlet transformation: servlet.setTransformWsdlLocations(true). If you visit http://localhost:8080/ws/countries.wsdl, the soap:address will have the proper address. If you instead visit the WSDL from the public facing IP address assigned to your machine, you will see that address instead.

Make the Application Executable

Spring Boot creates an application class for you. In this case, it needs no further modification. You can use it to run this application. The following listing (from src/main/java/com/example/producingwebservice/ shows the application class:

package com.example.producingwebservice;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

public class ProducingWebServiceApplication {

	public static void main(String[] args) {, args);

@SpringBootApplication is a convenience annotation that adds all of the following:

  • @Configuration: Tags the class as a source of bean definitions for the application context.

  • @EnableAutoConfiguration: Tells Spring Boot to start adding beans based on classpath settings, other beans, and various property settings. For example, if spring-webmvc is on the classpath, this annotation flags the application as a web application and activates key behaviors, such as setting up a DispatcherServlet.

  • @ComponentScan: Tells Spring to look for other components, configurations, and services in the com/example package, letting it find the controllers.

The main() method uses Spring Boot’s method to launch an application. Did you notice that there was not a single line of XML? There is no web.xml file, either. This web application is 100% pure Java and you did not have to deal with configuring any plumbing or infrastructure.

Build an executable JAR

You can run the application from the command line with Gradle or Maven. You can also build a single executable JAR file that contains all the necessary dependencies, classes, and resources and run that. Building an executable jar makes it easy to ship, version, and deploy the service as an application throughout the development lifecycle, across different environments, and so forth.

If you use Gradle, you can run the application by using ./gradlew bootRun. Alternatively, you can build the JAR file by using ./gradlew build and then run the JAR file, as follows:

java -jar build/libs/gs-soap-service-0.1.0.jar

If you use Maven, you can run the application by using ./mvnw spring-boot:run. Alternatively, you can build the JAR file with ./mvnw clean package and then run the JAR file, as follows:

java -jar target/gs-soap-service-0.1.0.jar
The steps described here create a runnable JAR. You can also build a classic WAR file.

Logging output is displayed. The service should be up and running within a few seconds.

Test the Application

Now that the application is running, you can test it. Create a file called request.xml that contains the following SOAP request:

<soapenv:Envelope xmlns:soapenv=""

The are a few options when it comes to testing the SOAP interface. You can use something similar to SoapUI or use command-line tools if you are on a *nix/Mac system. The following example uses curl from the command line:

# Use data from file
curl --header "content-type: text/xml" -d @request.xml http://localhost:8080/ws
# Use inline XML data
curl <<-EOF -fsSL -H "content-type: text/xml" -d @- http://localhost:8080/ws \
  > target/response.xml && xmllint --format target/response.xml

<soapenv:Envelope xmlns:soapenv=""


As a result, you should see the following response:

<?xml version="1.0"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="">
    <ns2:getCountryResponse xmlns:ns2="">
Odds are that the output will be a compact XML document instead of the nicely formatted one shown above. If you have xmllib2 installed on your system, you can curl -fsSL --header "content-type: text/xml" -d @request.xml http://localhost:8080/ws > output.xml and xmllint --format output.xml see the results formatted nicely.


Congratulations! You have developed a SOAP-based service with Spring Web Services.

See Also

The following guides may also be helpful:

Want to write a new guide or contribute to an existing one? Check out our contribution guidelines.

All guides are released with an ASLv2 license for the code, and an Attribution, NoDerivatives creative commons license for the writing.