You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Gradle,如何用Apache CXF+Spring Boot构建契约最后式SOAP Web服务?

Apache CXF与Spring Boot现有组件整合指南

针对你遇到的问题——已经完成数据访问层(JDBC DAO)和外观层开发,却不知道如何将Apache CXF整合到Spring Boot项目中,我整理了一套清晰的步骤,帮你快速搞定:

1. 补全Gradle依赖

首先确保你的build.gradle里包含Apache CXF的Spring Boot相关依赖,让Spring Boot自动配置CXF的基础组件:

dependencies {
    // 你已有的Spring Boot JDBC依赖
    implementation 'org.springframework.boot:spring-boot-starter-jdbc'
    // Apache CXF Spring Boot SOAP Starter核心依赖
    implementation 'org.apache.cxf:cxf-spring-boot-starter-jaxws'
    // 数据库驱动(根据你的实际数据库调整,比如MySQL)
    runtimeOnly 'com.mysql:mysql-connector-j'
}

2. 给外观层类添加SOAP注解

因为你用的是契约最后模式,直接在已有的外观层Service类上添加CXF的SOAP注解,把它标记为SOAP服务:

import javax.jws.WebMethod;
import javax.jws.WebService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

// serviceName自定义服务名,targetNamespace建议用项目包名反转格式
@WebService(serviceName = "UserService", targetNamespace = "http://yourcompany.com/soap")
@Service // 保留Spring Bean特性,方便注入DAO层
public class UserFacadeService {

    @Autowired
    private UserDao userDao; // 你已实现的数据访问层Bean

    @WebMethod(operationName = "getUserById")
    public UserDto getUserById(Long id) {
        // 直接调用DAO层方法,返回DTO即可
        return userDao.getUserById(id);
    }
}

提示:UserDto要保证可序列化,CXF会自动将其转化为SOAP消息的XML结构

3. 配置CXF端点,暴露SOAP服务

创建一个Spring配置类,注册CXF的Servlet,并把你的外观层类注册为SOAP端点:

import org.apache.cxf.Bus;
import org.apache.cxf.jaxws.EndpointImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.xml.ws.Endpoint;

@Configuration
public class CxfConfig {

    @Autowired
    private Bus bus;

    @Autowired
    private UserFacadeService userFacadeService;

    @Bean
    public Endpoint endpoint() {
        EndpointImpl endpoint = new EndpointImpl(bus, userFacadeService);
        // 这里的路径是SOAP服务的访问路径,最终地址为http://localhost:8080/services/user
        endpoint.publish("/user");
        return endpoint;
    }
}

4. 验证整合效果

启动Spring Boot应用后,通过以下方式验证:

  • 访问WSDL地址:http://localhost:8080/services/user?wsdl,能看到自动生成的WSDL文档,说明服务已成功暴露
  • 用SOAP UI或Postman发送SOAP请求,测试getUserById方法是否能正常调用DAO层并返回结果

关键注意事项

  • 确保你的DAO层Bean已被Spring正确管理(比如加@Repository注解),这样外观层可以直接通过@Autowired注入
  • 如果需要自定义CXF配置(比如日志拦截器、消息格式),可以在CxfConfig中添加对应的Bean,比如LoggingInInterceptor和LoggingOutInterceptor
  • 契约最后模式下,CXF会根据Java类自动生成WSDL,后续修改契约直接调整Java类即可,CXF会同步更新WSDL

内容的提问来源于stack exchange,提问作者lazha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:19:25