开篇词
该指南将引导你使用 Spring 完成基于 SOAP 的 Web 的服务。
你将创建的应用
我们将构建一个客户端,该客户端使用 SOAP 从基于 WSDL 的远程 Web 服务中获取国家/地区数据。我们可以按照该指南(尽请期待~)查找有关国家/地区服务的更多信息并自行运行该服务。
你将需要的工具
- 大概 15 分钟左右;
- 你最喜欢的文本编辑器或集成开发环境(IDE)
- JDK 1.8 或更高版本;
- Gradle 4+ 或 Maven 3.2+
- 你还可以将代码直接导入到 IDE 中:
如何完成这个指南
像大多数的 Spring 入门指南一样,你可以从头开始并完成每个步骤,也可以绕过你已经熟悉的基本设置步骤。如论哪种方式,你最终都有可以工作的代码。
- 要从头开始,移步至从 Spring Initializr 开始;
- 要跳过基础,执行以下操作:
- 下载并解压缩该指南将用到的源代码,或借助 Git 来对其进行克隆操作:
git clone https://github.com/spring-guides/gs-consuming-web-service.git
- 切换至
gs-consuming-web-service/initial
目录; - 跳转至该指南的基于 WSDL 来生成域对象。
- 下载并解压缩该指南将用到的源代码,或借助 Git 来对其进行克隆操作:
待一切就绪后,可以检查一下 gs-consuming-web-service/complete
目录中的代码。
如果你阅读了生产 SOAP Web 服务,你可能会想知道为什么该指南不使用
spring-boot-start-ws
?该 Spring Boot starter 仅用于服务器端 Web 服务。该 starter 可以使用嵌入式 Tomcat 之类的东西,而无需进行 Web 调用。
在本地运行目标 Web 服务
请遵循随附指南(尽请期待~)中的步骤,或克隆其代码并从 complete
目录运行服务(例如,使用 mvn spring-boot: run
(我需要这样才能运行:./mvnw spring-boot:run
))。我们可以通过在浏览器中访问 http://localhost:8080/ws/countries.wsdl 来验证其是否有效。
从 Spring Initializr 开始
对于所有的 Spring 应用来说,你应该从 Spring Initializr 开始。Initializr 提供了一种快速的方法来提取应用程序所需的依赖,并为你完成许多设置。该示例仅需要 Spring Web Services 依赖。下图显示了此示例项目的 Initializr 设置:
上图显示了选择 Maven 作为构建工具的 Initializr。你也可以使用 Gradle。它还将
com.example
和consuming-web-service
的值分别显示为 Group 和 Artifact。在本示例的其余部分,将用到这些值。
以下清单显示了选择 Maven 时创建的 pom.xml
文件:
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>consuming-web-service</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>consuming-web-service</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
以下清单显示了在选择 Gradle 时创建的 build.gradle
文件:
plugins {
id 'org.springframework.boot' version '2.2.0.RELEASE'
id 'io.spring.dependency-management' version '1.0.8.RELEASE'
id 'java'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter'
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
}
test {
useJUnitPlatform()
}
编辑构建文件
Spring Initializr 创建的构建文件需要大量的工作才能完成该指南。同样,对 pom.xml
(对于 Maven)和 build.gradle
(对于 Gradle)的修改也大不相同。
Maven
对于 Maven,我们需要添加依赖,配置文件和 WSDL 生成插件。
以下清单显示了我们需要在 Maven 中添加的依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
以下清单显示了要使其与 Java 11 一起使用时需要在 Maven 中添加的配置:
<profiles>
<profile>
<id>java11</id>
<activation>
<jdk>[11,)</jdk>
</activation>
<dependencies>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
</dependency>
</dependencies>
</profile>
</profiles>
基于 WSDL 来生成域对象部分介绍了 WSDL 生成插件。
以下清单显示了最终的 pom.xml
文件:
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.0.RELEASE</version>
<!-- lookup parent from repository -->
<relativePath/>
</parent>
<groupId>com.example</groupId>
<artifactId>consuming-web-service</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>consuming-web-service</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- tag::dependency[] -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web-services</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- end::dependency[] -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<!-- tag::profile[] -->
<profiles>
<profile>
<id>java11</id>
<activation>
<jdk>[11,)</jdk>
</activation>
<dependencies>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
</dependency>
</dependencies>
</profile>
</profiles>
<!-- end::profile[] -->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!-- tag::wsdl[] -->
<plugin>
<groupId>org.jvnet.jaxb2.maven2</groupId>
<artifactId>maven-jaxb2-plugin</artifactId>
<version>0.14.0</version>
<executions>
<execution>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
<configuration>
<schemaLanguage>WSDL</schemaLanguage>
<generatePackage>com.example.consumingwebservice.wsdl</generatePackage>
<schemas>
<schema>
<url>http://localhost:8080/ws/countries.wsdl</url>
</schema>
</schemas>
</configuration>
</plugin>
<!-- end::wsdl[] -->
</plugins>
</build>
</project>
Gradle
对于 Gradle,我们需要添加依赖、配置、bootJar 部分及 WSDL 生成插件。
以下清单显示了我们需要在 Gradle 中添加的依赖:
implementation ('org.springframework.boot:spring-boot-starter-web-services') {
exclude group: 'org.springframework.boot', module: 'spring-boot-starter-tomcat'
}
implementation 'org.springframework.ws:spring-ws-core'
// For Java 11:
implementation 'org.glassfish.jaxb:jaxb-runtime'
compile(files(genJaxb.classesDir).builtBy(genJaxb))
jaxb "com.sun.xml.bind:jaxb-xjc:2.1.7"
注意要排除 Tomcat。如果允许 Tomcat 在该版本中运行,则将与提供国家/地区数据的 Tomcat 实例发生端口冲突。
以下清单显示了我们需要在 Gradle 中添加的 bootJar 部分:
bootJar {
baseName = 'gs-consuming-web-service'
version = '0.0.1'
}
基于 WSDL 来生成域对象部分介绍了 WSDL 生成插件。
以下清单显示了最终的 build.gradle
文件:
plugins {
id 'org.springframework.boot' version '2.2.0.RELEASE'
id 'io.spring.dependency-management' version '1.0.8.RELEASE'
id 'java'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
// tag::configurations[]
configurations {
jaxb
}
// end::configurations[]
repositories {
mavenCentral()
}
// tag::wsdl[]
task genJaxb {
ext.sourcesDir = "${buildDir}/generated-sources/jaxb"
ext.classesDir = "${buildDir}/classes/jaxb"
ext.schema = "http://localhost:8080/ws/countries.wsdl"
outputs.dir classesDir
doLast() {
project.ant {
taskdef name: "xjc", classname: "com.sun.tools.xjc.XJCTask",
classpath: configurations.jaxb.asPath
mkdir(dir: sourcesDir)
mkdir(dir: classesDir)
xjc(destdir: sourcesDir, schema: schema,
package: "com.example.consumingwebservice.wsdl") {
arg(value: "-wsdl")
produces(dir: sourcesDir, includes: "**/*.java")
}
javac(destdir: classesDir, source: 1.8, target: 1.8, debug: true,
debugLevel: "lines,vars,source",
classpath: configurations.jaxb.asPath) {
src(path: sourcesDir)
include(name: "**/*.java")
include(name: "*.java")
}
copy(todir: classesDir) {
fileset(dir: sourcesDir, erroronmissingdir: false) {
exclude(name: "**/*.java")
}
}
}
}
}
// end::wsdl[]
dependencies {
// tag::dependency[]
implementation ('org.springframework.boot:spring-boot-starter-web-services') {
exclude group: 'org.springframework.boot', module: 'spring-boot-starter-tomcat'
}
implementation 'org.springframework.ws:spring-ws-core'
// For Java 11:
implementation 'org.glassfish.jaxb:jaxb-runtime'
compile(files(genJaxb.classesDir).builtBy(genJaxb))
jaxb "com.sun.xml.bind:jaxb-xjc:2.1.7"
// end::dependency[]
testImplementation('org.springframework.boot:spring-boot-starter-test') {
exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
}
}
test {
useJUnitPlatform()
}
// tag::bootjar[]
bootJar {
baseName = 'gs-consuming-web-service'
version = '0.0.1'
}
// end::bootjar[]
基于 WSDL 来生成域对象
WSDL 中捕获了 SOAP Web 服务的接口。JAXB 提供了一种从 WSDL(更确切地说,包含在 WSDL的 <Types/>
部分中的 XSD)生成 Java 类的方法。我们可以在 http://localhost:8080/ws/countries.wsdl 中找到国家服务的 WSDL。
要从 Maven 中的 WSDL 生成 Java 类,我们需要配置好以下插件:
<plugin>
<groupId>org.jvnet.jaxb2.maven2</groupId>
<artifactId>maven-jaxb2-plugin</artifactId>
<version>0.14.0</version>
<executions>
<execution>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
<configuration>
<schemaLanguage>WSDL</schemaLanguage>
<generatePackage>com.example.consumingwebservice.wsdl</generatePackage>
<schemas>
<schema>
<url>http://localhost:8080/ws/countries.wsdl</url>
</schema>
</schemas>
</configuration>
</plugin>
该配置将为在指定的 URL 处找到的 WSDL 生成类,并将这些类放入 com.example.usingwebservice.wsdl
包中。要生成该代码,请运行 ./mvnw compile
,然后在 target/generated-sources
中查找,如果我们想检查它是否起作用。
要对 Gradle 进行同样的操作,我们的构建文件中将需要以下内容:
task genJaxb {
ext.sourcesDir = "${buildDir}/generated-sources/jaxb"
ext.classesDir = "${buildDir}/classes/jaxb"
ext.schema = "http://localhost:8080/ws/countries.wsdl"
outputs.dir classesDir
doLast() {
project.ant {
taskdef name: "xjc", classname: "com.sun.tools.xjc.XJCTask",
classpath: configurations.jaxb.asPath
mkdir(dir: sourcesDir)
mkdir(dir: classesDir)
xjc(destdir: sourcesDir, schema: schema,
package: "com.example.consumingwebservice.wsdl") {
arg(value: "-wsdl")
produces(dir: sourcesDir, includes: "**/*.java")
}
javac(destdir: classesDir, source: 1.8, target: 1.8, debug: true,
debugLevel: "lines,vars,source",
classpath: configurations.jaxb.asPath) {
src(path: sourcesDir)
include(name: "**/*.java")
include(name: "*.java")
}
copy(todir: classesDir) {
fileset(dir: sourcesDir, erroronmissingdir: false) {
exclude(name: "**/*.java")
}
}
}
}
}
由于 Gradle 还没有 JAXB 插件,因此涉及 Ant 任务,这使其比 Maven 复杂。要生成该代码,请运行 ./gradlew compileJava
,然后在 build/generated-sources
中查看其是否已生成。
在这两种情况下,JAXB 域对象的生成过程都已连接到构建工具的生命周期中,因此,一旦构建成功,就无需再执行任何其他步骤。
创建国家服务客户端
要创建 Web 服务客户端,我们必须扩展 WebServiceGatewaySupport
类并编写操作代码,如以下示例(来自 src/main/java/com/example/consumingwebservice/CountryClient.java
)所示:
package com.example.consumingwebservice;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ws.client.core.support.WebServiceGatewaySupport;
import org.springframework.ws.soap.client.core.SoapActionCallback;
import com.example.consumingwebservice.wsdl.GetCountryRequest;
import com.example.consumingwebservice.wsdl.GetCountryResponse;
public class CountryClient extends WebServiceGatewaySupport {
private static final Logger log = LoggerFactory.getLogger(CountryClient.class);
public GetCountryResponse getCountry(String country) {
GetCountryRequest request = new GetCountryRequest();
request.setName(country);
log.info("Requesting location for " + country);
GetCountryResponse response = (GetCountryResponse) getWebServiceTemplate()
.marshalSendAndReceive("http://localhost:8080/ws/countries", request,
new SoapActionCallback(
"http://spring.io/guides/gs-producing-web-service/GetCountryRequest"));
return response;
}
}
客户端包含一种进行实际 SOAP 交换的方法(getCountry
)。
在该方法中,GetCountryRequest
和 GetCountryResponse
类均从 WSDL 派生,并在 JAXB 生成过程中生成(在基于 WSDL 的生成域对象中进行了介绍)。它创建 GetCountryRequest
请求对象,并使用 country
参数(国家名称)进行设置。在打印出国家/地区名称后,它使用 WebServiceGatewaySupport
基类提供的 WebServiceTemplate
进行实际的 SOAP 交换。当 WSDL 描述它需要 <soap:operation/>
元素中的该标头时,它传递 GetCountryRequest
请求对象(以及一个 SoapActionCallback
来将请求传递给 SOAPAction 标头)。它将响应转换为 GetCountryResponse
对象,然后将其返回。
配置 Web 服务组件
Spring WS 使用 Spring 框架的 OXM 模块,该模块具有 Jaxb2Marshaller
来对 XML 请求进行序列化和反序列化,如以下示例(来自 src/main/java/com/example/consumingwebservice/CountryConfiguration.java
)所示:
package com.example.consumingwebservice;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
@Configuration
public class CountryConfiguration {
@Bean
public Jaxb2Marshaller marshaller() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
// this package must match the package in the <generatePackage> specified in
// pom.xml
marshaller.setContextPath("com.example.consumingwebservice.wsdl");
return marshaller;
}
@Bean
public CountryClient countryClient(Jaxb2Marshaller marshaller) {
CountryClient client = new CountryClient();
client.setDefaultUri("http://localhost:8080/ws");
client.setMarshaller(marshaller);
client.setUnmarshaller(marshaller);
return client;
}
}
marshaller
指向生成的域对象的集合,并将使用它们在 XML 和 POJO 之间进行序列化和反序列化。
将使用先前显示的国家/地区服务的 URI 创建并配置 countryClient
。它还被配置为使用 JAXB 转换器。
运行应用
该应用已打包为可从控制台运行并检索给定国家/地区名称的数据,如以下清单(来自 src/main/java/com/example/consumingwebservice/ConsumingWebServiceApplication.java
)所示:
package com.example.consumingwebservice;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import com.example.consumingwebservice.wsdl.GetCountryResponse;
@SpringBootApplication
public class ConsumingWebServiceApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumingWebServiceApplication.class, args);
}
@Bean
CommandLineRunner lookup(CountryClient quoteClient) {
return args -> {
String country = "Spain";
if (args.length > 0) {
country = args[0];
}
GetCountryResponse response = quoteClient.getCountry(country);
System.err.println(response.getCountry().getCurrency());
};
}
}
main()
方法遵循 SpringApplication
帮助类,提供 CountryConfiguration.class
作为其 run()
方法的参数。这告诉 Spring 从 CountryConfiguration
读取注解元数据,并将其作为 Spring 应用上下文的组件进行管理。
该应用通过硬编码以查找 ‘Spain’。在该指南后面,我们将看到如何在不编辑代码的情况下输入其他符号。
构建可执行 JAR
我们可以结合 Gradle 或 Maven 来从命令行运行该应用。我们还可以构建一个包含所有必须依赖项、类以及资源的可执行 JAR 文件,然后运行该文件。在整个开发生命周期中,跨环境等等情况下,构建可执行 JAR 可以轻松地将服务作为应用进行发布、版本化以及部署。
如果使用 Gradle,则可以借助 ./gradlew bootRun
来运行应用。或通过借助 ./gradlew build
来构建 JAR 文件,然后运行 JAR 文件,如下所示:
java -jar build/libs/gs-consuming-web-service-0.1.0.jar
由官网提供的以上这条命令的执行结果与我本地的不一样,我需要这样才能运行:
java -jar build/libs/gs-consuming-web-service-0.0.1.jar
。
如果使用 Maven,则可以借助 ./mvnw spring-boot:run
来运行该用。或可以借助 ./mvnw clean package
来构建 JAR 文件,然后运行 JAR 文件,如下所示:
java -jar target/gs-consuming-web-service-0.1.0.jar
由官网提供的以上这条命令的执行结果与我本地的不一样,我需要这样才能运行:
java -jar target/consuming-web-service-0.0.1-SNAPSHOT.jar
。
我们还可以将 JAR 应用转换成 WAR 应用。
显示日志记录输出。该服务应在几秒内启动并运行。
以下清单显示了初始响应:
Requesting country data for Spain
<getCountryRequest><name>Spain</name>...</getCountryRequest>
我们可以通过运行以下命令来插入其他国家/地区:
java -jar build/libs/gs-consuming-web-service-0.0.1.jar Poland
然后,响应更改为以下内容:
Requesting location for Poland
<getCountryRequest><name>Poland</name>...</getCountryRequest>
概述
恭喜你!我们刚刚开发了一个客户端,可以使用 Spring 使用基于 SOAP 的 Web 服务。
参见
以下指南也可能会有所帮助:
想看指南的其他内容?请访问该指南的所属专栏:《Spring 官方指南》