SpringBoot 整合 Apache CXF

本文介绍了如何在Spring Boot项目中集成Apache CXF,实现RESTful API,包括依赖管理、User实体类定义、IUserService接口及其实现、配置文件和测试。重点展示了如何处理JSON数据和使用Jackson作为JSON provider。

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

demo项目地址:https://gitee.com/Jxnuxyhsz/cxf-demo

导入依赖

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <!-- jaxrs : CXF Restful webservice -->
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-spring-boot-starter-jaxrs</artifactId>
            <version>3.2.4</version>
            <exclusions>
                <!--The Bean Validation API is on the classpath but no implementation could be found-->
                <exclusion>
                    <groupId>javax.validation</groupId>
                    <artifactId>validation-api</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!--Google Guice 一个轻量级的依赖注入框架-->
        <dependency>
            <groupId>com.google.inject</groupId>
            <artifactId>guice</artifactId>
            <version>4.0</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.jaxrs/jackson-jaxrs-json-provider -->
        <dependency>
            <groupId>com.fasterxml.jackson.jaxrs</groupId>
            <artifactId>jackson-jaxrs-json-provider</artifactId>
            <version>2.12.3</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.13</version>
        </dependency>

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

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

domain

/**
 *  User实体类
 */
@Data
@AllArgsConstructor
@XmlRootElement // 对象转换成xml/json
public class User implements Serializable {
    private static final long serialVersionUID = -2561117553127467595L;

    // 工号
    private Long userId;

    // 姓名
    private String userName;

    // 住址
    private String address;
}

IUserService

/**
 *  User接口
 *
 */
@Path("/users")
@Produces(value = {MediaType.APPLICATION_JSON}) // 返回json格式
public interface IUserService {

    /**
     * 返回指定userIdD的user信息
     *
     * @param userId
     * @return User
     */
    @GET
    @Path("/{userId}")
    User selectUserInfo(@PathParam("userId") Long userId);
}

UserServiceImpl

@Named
public class UserServiceImpl implements IUserService {
    @Override
    public User selectUserInfo(Long userId) {
        return new User(userId, "JxnuXYH...", "JiangXi");
    }
}

application.properties

server.port=8080
server.servlet.context-path=/demo

cxf-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxrs="http://cxf.apache.org/jaxrs"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
       http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 扫描注解 -->
    <context:component-scan base-package="com.example.demo"/>
    <!-- 暴露Service -->
    <jaxrs:server id="restContainer" address="/rest">
        <jaxrs:serviceBeans>
            <ref bean="userServiceImpl" />
        </jaxrs:serviceBeans>
        <jaxrs:providers>   <!-- json转化 -->
            <ref bean="jacksonJsonProvider" />
        </jaxrs:providers>
    </jaxrs:server>
</beans>

DemoApplication

@SpringBootApplication
@ImportResource(locations = "classpath:cxf-config.xml")
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Bean
    public JacksonJsonProvider jacksonJsonProvider(){
        return new JacksonJsonProvider();
    }
}

访问测试

在这里插入图片描述

在这里插入图片描述

ClientTest

/**
 *  模拟客户端访问测试
 *  使用httpClient访问
 */
public class ClientTest {
    public static void main(String[] args) {
        // 获取httpClient
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        // 创建请求
        HttpGet httpGet = new HttpGet("http://localhost:8080/demo/services/rest/users/123");

        // 响应类型
        CloseableHttpResponse response = null;
        InputStream inputStream = null;
        try{
          response = httpClient.execute(httpGet);
          HttpEntity entity = response.getEntity();
          if (entity != null) {
              inputStream = entity.getContent();
              int len = 0; // 记录读取长度
              int tmp;
              byte[] data = new byte[1024]; // 开辟一个空间
              while ((tmp = inputStream.read()) != -1) {
                  data[len++] = (byte) tmp; // 保存在字节数组中
              }
              System.out.println("客户端访问到的内容: " + new String(data, 0, len));
          }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

// 客户端访问到的内容: {"userId":123,"userName":"JxnuXYH...","address":"JiangXi"}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值