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.
What You Need
About 15 minutes
A favorite text editor or IDE
Java 17 or later
Gradle 7.5+ or Maven 3.5+
You can also import the code straight into your IDE:
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:
Download and unzip the source repository for this guide, or clone it using Git: git clone https://github.com/spring-guides/gs-soap-service.git
cd into gs-soap-service/initial
Jump ahead to Add the Spring-WS dependency.
When you finish, you can check your results against the code in gs-soap-service/complete .
Starting with Spring Initializr
You can use this pre-initialized project and click Generate to download a ZIP file. This project is configured to fit the examples in this tutorial.
Navigate to https://start.spring.io. This service pulls in all the dependencies you need for an application and does most of the setup for you.
Choose either Gradle or Maven and the language you want to use. This guide assumes that you chose Java.
Click Dependencies and select Spring Web and Spring Web Services.
Click Generate.
Download the resulting ZIP file, which is an archive of a web application that is configured with your choices.
Both the pom.xml and build.gradle files need 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:
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:
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:
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:
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/CountryRepository.java ) shows how to do so:
package com.example.producingwebservice; import jakarta.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; @Component public class CountryRepository < private static final Mapcountries = new HashMap<>(); @PostConstruct public void initData() < Country spain = new Country(); spain.setName("Spain"); spain.setCapital("Madrid"); spain.setCurrency(Currency.EUR); spain.setPopulation(46704314); countries.put(spain.getName(), spain); Country poland = new Country(); poland.setName("Poland"); poland.setCapital("Warsaw"); poland.setCurrency(Currency.PLN); poland.setPopulation(38186860); countries.put(poland.getName(), poland); Country uk = new Country(); uk.setName("United Kingdom"); uk.setCapital("London"); uk.setCurrency(Currency.GBP); uk.setPopulation(63705000); 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/CountryEndpoint.java ) shows such a class:
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/WebServiceConfig.java ) 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.core.io.ClassPathResource; import org.springframework.ws.config.annotation.EnableWs; import org.springframework.ws.config.annotation.WsConfigurerAdapter; import org.springframework.ws.transport.http.MessageDispatcherServlet; import org.springframework.ws.wsdl.wsdl11.DefaultWsdl11Definition; import org.springframework.xml.xsd.SimpleXsdSchema; import org.springframework.xml.xsd.XsdSchema; @EnableWs @Configuration public class WebServiceConfig extends WsConfigurerAdapter < @Bean public ServletRegistrationBeanmessageDispatcherServlet(ApplicationContext applicationContext) < MessageDispatcherServlet servlet = new MessageDispatcherServlet(); servlet.setApplicationContext(applicationContext); servlet.setTransformWsdlLocations(true); return new ServletRegistrationBean<>(servlet, "/ws/*"); > @Bean(name = "countries") public DefaultWsdl11Definition defaultWsdl11Definition(XsdSchema countriesSchema) < DefaultWsdl11Definition wsdl11Definition = new DefaultWsdl11Definition(); wsdl11Definition.setPortTypeName("CountriesPort"); wsdl11Definition.setLocationUri("/ws"); wsdl11Definition.setTargetNamespace("http://spring.io/guides/gs-producing-web-service"); wsdl11Definition.setSchema(countriesSchema); return wsdl11Definition; >@Bean public XsdSchema countriesSchema() < return new SimpleXsdSchema(new ClassPathResource("countries.xsd")); >>
Spring WS uses a different servlet type for handling SOAP messages: MessageDispatcherServlet . It is important to inject and set ApplicationContext to MessageDispatcherServlet . Without that, Spring WS will not automatically detect Spring beans.
Naming this bean messageDispatcherServlet does not replace Spring Boot’s default DispatcherServlet bean.
DefaultMethodEndpointAdapter configures the annotation-driven Spring WS programming model. This makes it possible to use the various annotations, such as @Endpoint (mentioned earlier).
DefaultWsdl11Definition exposes a standard WSDL 1.1 by using XsdSchema
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://:/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/ProducingWebServiceApplication.java ) shows the application class:
package com.example.producingwebservice; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ProducingWebServiceApplication < public static void main(String[] args) < SpringApplication.run(ProducingWebServiceApplication.class, 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 SpringApplication.run() 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
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:
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 target/response.xml && xmllint --format target/response.xml Spain EOF
As a result, you should see the following response:
Spain46704314MadridEUR
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.
Summary
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.