在Spring框架中调用WSDL定义的Web服务是一种常见的需求。以下是将WSDL文件转换为服务接口并使用Spring进行调用的详细步骤:
1. 添加依赖
首先,确保你的项目中包含了Spring WebServices和Spring Core的依赖。以下是一个典型的pom.xml文件中的依赖配置:
<dependencies>
<!-- Spring Core -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.3.10</version>
</dependency>
<!-- Spring WebServices -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web-services</artifactId>
<version>5.3.10</version>
</dependency>
<!-- Apache CXF Client -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<version>3.4.0</version>
</dependency>
</dependencies>
2. 创建服务客户端
使用Spring的JaxWsProxyFactoryBean来创建一个服务客户端。你需要指定WSDL文件的URL和服务接口的类。
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.ws.client.core.WebServiceTemplate;
import org.springframework.ws.soap.client.core.SoapActionCallback;
public class ServiceClient {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
WebServiceTemplate webServiceTemplate = (WebServiceTemplate) context.getBean("wsTemplate");
MyServicePortType servicePortType = (MyServicePortType) webServiceTemplate.getBean("myServicePort");
// 调用服务方法
String result = servicePortType.myOperation("some input");
System.out.println("Service Result: " + result);
}
}
3. 配置文件
在Spring的配置文件中配置JaxWsProxyFactoryBean,指定WSDL文件和服务接口。
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- JaxWsProxyFactoryBean 配置 -->
<bean id="wsTemplate" class="org.springframework.ws.client.core.WebServiceTemplate">
<property name="messageFactory">
<bean class="org.springframework.ws.client.support.WebServiceMappingMessageFactory"/>
</property>
</bean>
<!-- JaxWsProxyFactoryBean 配置 -->
<bean id="myServicePort" class="org.springframework.ws.client.core.JaxWsProxyFactoryBean">
<property name="serviceInterface" value="com.example.MyServicePortType"/>
<property name="address" value="http://example.com/myService?wsdl"/>
</bean>
</beans>
4. 服务接口
创建一个接口,该接口与WSDL文件中的操作相对应。
import javax.jws.WebService;
@WebService
public interface MyServicePortType {
String myOperation(String input);
}
5. 运行客户端
运行ServiceClient类中的main方法,你将看到从远程服务返回的结果。
注意事项
- 确保WSDL文件中的命名空间与配置文件中的
address属性和接口中的@WebService注解中的targetNamespace属性相匹配。 - 如果WSDL文件中有复杂的类型定义,可能需要在Spring配置文件中添加相应的类型转换器。
- 检查WSDL文件中的
wsdl:service元素中的name属性值,确保与配置文件中的JaxWsProxyFactoryBean的serviceInterface属性值相匹配。
通过以上步骤,你可以在Spring框架中成功调用由WSDL定义的Web服务。
