springboot集成cxf

本文介绍了如何在SpringBoot项目中集成ApacheCXF,包括添加依赖、配置WebService、创建接口和实现、以及使用Postman测试SOAP服务。展示了如何使用CXF创建支持多种协议的服务并配置线程池和日志拦截。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、Apache CXF是什么?

Apache CXF 是一个开源的 Services 框架,CXF 帮助您利用 Frontend 编程 API 来构建和开发 Services ,像 JAX-WS 。这些 Services 可以支持多种协议,比如:SOAP、XML/HTTP、RESTful HTTP 或者 CORBA ,并且可以在多种传输协议上运行,比如:HTTP、JMS 或者 JBI,CXF 大大简化了 Services 的创建,同时它继承了 XFire 传统,一样可以天然地和 Spring 进行无缝集成。

二、SpringBoot集成CXF

1、POM依赖

<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.syx</groupId>
    <artifactId>cxf-learn</artifactId>
    <version>1.0-SNAPSHOT</version>
    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <cxf.version>3.2.4</cxf.version>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>


    <dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- webService-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web-services</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-spring-boot-starter-jaxws</artifactId>
            <version>3.2.4</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>5.4.1.Final</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.12.0</version>
        </dependency>
    </dependencies>

</project>

2、WebService配置

该配置用于发布WebService服务同时配置了业务线程池及服务的输入输出拦截器,用于监控服务交易情况。

package com.cxf.config;

import com.cxf.endpoint.Service;
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
import org.apache.cxf.bus.spring.SpringBus;
import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
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.jws.WebService;
import javax.xml.ws.Endpoint;
import java.util.Collections;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Author whh
 * Date 2023/12/07/ 22:39
 * <p></p>
 */
@Configuration
public class WebServiceConfig {

    @Autowired
    private SpringBus bus;

    @Autowired
    private Service service;
    @Bean
    public Endpoint endpoint() {
        EndpointImpl endpoint = new EndpointImpl(bus,service);
        endpoint.setInInterceptors(Collections.singletonList(new LoggingInInterceptor()));
        endpoint.setOutInterceptors(Collections.singletonList(new LoggingOutInterceptor()));

        //将serviceName作为线程池前缀
        WebService annotation = service.getClass().getAnnotation(WebService.class);
        String prefix = annotation.serviceName();
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                10,
                50,
                2L,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(),
                new BasicThreadFactory.Builder().namingPattern(prefix+"-thread-pool-%d").daemon(true).build(),
                new ThreadPoolExecutor.CallerRunsPolicy());

        //设置线程池
        endpoint.setExecutor(executor);
        endpoint.publish("/api");
        return endpoint;
    }
}

3、WebService接口

package com.cxf.endpoint;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;

/**
 * Author whh
 * Date 2023/12/07/ 22:22
 * <p></p>
 */
@WebService(targetNamespace = "http://com.cxf.endpoint.Service")
public interface Service {
    @WebMethod
    String sayHello(@WebParam(name = "name")String name);
}

4、WebService接口实现类

package com.cxf.endpoint;

import org.springframework.stereotype.Component;

import javax.jws.WebService;

/**
 * Author whh
 * Date 2023/12/07/ 22:35
 * <p></p>
 */

@WebService(serviceName = "Service",
        targetNamespace = "http://com.cxf.endpoint.Service",//指定你想要的名称空间,通常使用使用包名反转
        endpointInterface = "com.cxf.endpoint.Service")
@Component
public class ServiceImpl implements Service {
    @Override
    public String sayHello(String name) {

        System.out.println(Thread.currentThread().getName());
        return "Hello,"+name;
    }
}

5、配置文件
server:
  servlet:
    context-path: /primal
  port: 8080



cxf:
  path: /cxf

6、启动类
package com.cxf;

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

/**
 *
 * Author whh
 * Date 2023/12/07/ 21:36
 * <p></p>
 */
@SpringBootApplication
public class MainApp {

    public static void main(String[] args) {
        SpringApplication.run(MainApp.class);
    }

}

7、查看项目暴露的service列表

访问地址 http://localhost:8080/primal/cxf/
可以看到咱们这个项目中发布的一个service

在这里插入图片描述

8、查看具体某个service的wsdl文档

访问地址 http://localhost:8080/primal/cxf/api?wsdl
即查看api对应的wsdl文档

在这里插入图片描述

9、测试
import com.cxf.endpoint.Service;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.frontend.ClientProxy;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.apache.cxf.transport.http.HTTPConduit;
import org.apache.cxf.transports.http.configuration.HTTPClientPolicy;

/**
 * Author whh
 * Date 2023/12/07/ 22:58
 * <p></p>
 */
public class MainTest {


    public static void main(String[] args) {

        String address = "http://127.0.0.1:8080/primal/cxf/api/Service";
        // 代理工厂
        JaxWsProxyFactoryBean jaxWsProxyFactoryBean = new JaxWsProxyFactoryBean();
        // 设置代理地址
        jaxWsProxyFactoryBean.setAddress(address);
        // 设置接口类型
        jaxWsProxyFactoryBean.setServiceClass(Service.class);
        // 创建一个代理接口实现
        Service xmlEndPoint = (Service) jaxWsProxyFactoryBean.create();

        Client proxy = ClientProxy.getClient(xmlEndPoint);
        HTTPConduit conduit = (HTTPConduit) proxy.getConduit();
        HTTPClientPolicy policy = new HTTPClientPolicy();
        policy.setConnectionTimeout(5000);
        policy.setReceiveTimeout(5000);
        conduit.setClient(policy);

        String service = xmlEndPoint.sayHello("123");

        System.out.println(service);

    }
}

在这里插入图片描述

从上图中的日志可看出在处理业务逻辑的时候使用的是我们配置的业务线程池。

10、postman发送soap报文测试

请求报文:

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
     <soap:Body>
          <ns2:sayHello xmlns:ns2="http://com.cxf.endpoint.Service">
               <name>123</name>
          </ns2:sayHello>
     </soap:Body>
</soap:Envelope>

在这里插入图片描述

### 如何在 Spring Boot 中集成 Apache CXF 实现 Web Services #### 创建 Maven 或 Gradle 项目并引入依赖项 为了使 Spring Boot 应用程序能够支持 Web Service 功能,需向 `pom.xml` 文件中加入如下依赖: ```xml <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-spring-boot-starter-jaxws</artifactId> <version>${cxf.version}</version> </dependency> ``` 此操作确保了所需的所有库都被正确加载到工程里[^1]。 #### 编写服务接口和服务实现类 定义一个 JAX-WS 接口以及相应的实现类来提供具体的服务逻辑。例如: ```java import javax.jws.WebService; @WebService public interface HelloService { String sayHello(String name); } ``` 接着编写该接口的一个简单实现版本: ```java import javax.jws.WebService; import org.springframework.stereotype.Service; @Service("helloService") @WebService(endpointInterface = "com.example.HelloService", serviceName="HelloServiceImplService") public class HelloServiceImpl implements HelloService { @Override public String sayHello(String text) { return "Hello " + text; } } ``` 上述代码片段展示了如何通过标注 `@WebService` 来指定这是一个 web service 组件,并指定了其对应的 WSDL 名称和服务名称[^2]。 #### 配置 CXF 的路径和其他设置 编辑位于 `src/main/resources/application.properties` 下的应用属性文件,添加必要的配置参数以启用 CXF 并设定访问路径: ```properties server.port=8081 cxf.path=/webservices spring.main.allow-bean-definition-overriding=true ``` 这里设置了服务器监听端口号为 8081 和 CXF 发布的 URL 前缀 `/webservices` 。最后一行允许覆盖默认 Bean 定义以便于自定义组件注册[^4]。 #### 启动器类中的自动装配与发布服务 最后一步是在启动器类上标记 `@Import(CxfConfig.class)` 注解从而导入额外的配置信息;同时利用 `@ComponentScan(basePackages={"com"})` 扫描包内的所有组件。另外还需创建一个新的 Java 类用于声明要发布的服务列表: ```java @Configuration @ComponentScan(basePackages={"com"}) @EnableWs @ImportResource({"classpath:META-INF/cxf/cxf.xml","classpath*:META-INF/cxf/cxf-extension-soap.xml", "classpath*:META-INF/cxf/cxf-servlet.xml"}) public class CxfConfig { @Bean public Endpoint endpoint() { final EndpointImpl endpoint = new EndpointImpl(SpringBusFactory.getDefaultBus(), helloService()); endpoint.publish("/Hello"); return endpoint; } @Autowired private HelloService helloService; } ``` 这段代码实现了对之前定义好的 `HelloService` 进行实例化并通过 CXF 发布出去的过程[^3]。 完成以上步骤之后就可以成功地在一个标准的 Spring Boot 工程内集成了 Apache CXF ,进而可以方便快捷地构建起功能强大的 Web Service 应用了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值