SpringBoot集成CXF

article/2025/9/13 21:57:25
  1. CXF入门篇
    https://blog.csdn.net/tongxin_tongmeng/article/details/126482362
  2. Server端项目结构
    e54b301d167b44df8f5848c4b772dcc2.png
  3.  Server端pom.xml
    <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.cxf.webservice</groupId><artifactId>WS_Server</artifactId><version>0.0.1-SNAPSHOT</version><dependencies><!-- springboot webservice --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web-services</artifactId></dependency><!-- cxf webservice --><dependency><groupId>org.apache.cxf</groupId><artifactId>cxf-spring-boot-starter-jaxws</artifactId><version>3.2.14</version></dependency><!--JDK11需要添加此依赖--><dependency><groupId>com.sun.xml.ws</groupId><artifactId>jaxws-ri</artifactId><version>2.3.1</version></dependency></dependencies>
    </project>
  4.  Server端实体类
    package com.cxf.entity;import java.util.List;public class MyRole {private String key;private List<Role> value;public String getKey() {return key;}public void setKey(String key) {this.key = key;}public List<Role> getValue() {return value;}public void setValue(List<Role> value) {this.value = value;}}
    
    package com.cxf.entity;public class Role {private Integer id;private String roleName;public Role() {super();// TODO Auto-generated constructor stub}public Role(Integer id, String roleName) {super();this.id = id;this.roleName = roleName;}public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getRoleName() {return roleName;}public void setRoleName(String roleName) {this.roleName = roleName;}}
    
    package com.cxf.entity;public class User {private Integer id;private String userName;private String password;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}}
    
  5. Server端接口
    package com.cxf.webservice;import com.cxf.adapter.MapAdapter;
    import com.cxf.entity.Role;
    import com.cxf.entity.User;import java.util.List;
    import java.util.Map;import javax.jws.WebMethod;
    import javax.jws.WebParam;
    import javax.jws.WebService;
    import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;@WebService(name="HelloWorld", targetNamespace = "webservice.cxf.com")
    public interface HelloWorld {@WebMethod(operationName = "say")public String say(@WebParam(name = "str") String str);@WebMethod(operationName = "getRoleByUser")public List<Role> getRoleByUser(@WebParam(name = "user") User user);@XmlJavaTypeAdapter(MapAdapter.class)@WebMethod(operationName = "getRoles")public Map<String,List<Role>> getRoles();}
    
  6. Server端接口实现
     
    package com.cxf.webservice.impl;import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;import javax.jws.WebService;import com.cxf.entity.Role;
    import com.cxf.entity.User;
    import com.cxf.webservice.HelloWorld;
    import org.springframework.stereotype.Component;@Component
    public class HelloWorldImpl implements HelloWorld{public String say(String str) {return "Hello:"+str;}public List<Role> getRoleByUser(User user) {List<Role> roleList=new ArrayList<Role>();roleList.add(new Role(1,"AAAA"));roleList.add(new Role(2,"BBBB"));return roleList;}public Map<String, List<Role>> getRoles() {Map<String,List<Role>> map=new HashMap<String,List<Role>>();List<Role> roleList1=new ArrayList<Role>();roleList1.add(new Role(1,"CCCC"));map.put("cccc", roleList1);List<Role> roleList2=new ArrayList<Role>();roleList2.add(new Role(2,"DDDD"));map.put("dddd", roleList2);return map;}}
    
  7. Map类型返回值适配器
     
    package com.cxf.adapter;import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.Set;import javax.xml.bind.annotation.adapters.XmlAdapter;import com.cxf.entity.MyRole;
    import com.cxf.entity.Role;public class MapAdapter extends XmlAdapter<MyRole[], Map<String,List<Role>>>{/*** 适配转换 MyRole[] -> Map<String, List<Role>>*/@Overridepublic Map<String, List<Role>> unmarshal(MyRole[] myRoles) throws Exception {Map<String, List<Role>> map=new HashMap<String,List<Role>>();for(int i=0;i<myRoles.length;i++){MyRole myRole=myRoles[i];map.put(myRole.getKey(), myRole.getValue());}return map;}/*** 适配转换 Map<String, List<Role>> -> MyRole[]*/@Overridepublic MyRole[] marshal(Map<String, List<Role>> map) throws Exception {MyRole[] roles=new MyRole[map.size()];Set<Map.Entry<String, List<Role>>> entries = map.entrySet();Integer index = 0;for (Map.Entry<String, List<Role>> entry : entries) {roles[index]=new MyRole();roles[index].setKey(entry.getKey());roles[index].setValue(entry.getValue());index++;}return roles;}}
    
  8. Server端自定义拦截器(调用接口方法前执行) 
    package com.cxf.interceptor;import org.apache.cxf.binding.soap.SoapMessage;
    import org.apache.cxf.databinding.DataBinding;
    import org.apache.cxf.headers.Header;
    import org.apache.cxf.interceptor.Fault;
    import org.apache.cxf.phase.AbstractPhaseInterceptor;
    import org.apache.cxf.phase.Phase;
    import org.w3c.dom.Element;import javax.xml.namespace.QName;
    import java.util.List;public class MyInterceptor extends AbstractPhaseInterceptor<SoapMessage> {public MyInterceptor() {super(Phase.PRE_INVOKE);  // 在调用方法之前调用自定拦截器}@SuppressWarnings("null")public void handleMessage(SoapMessage message) throws Fault {List<Header> headers = message.getHeaders();
    //		throw new Fault(new IllegalArgumentException("#############"+headers.size()));
    //		for (Header header : headers) {
    //			Element ele=(Element) header.getObject();
    //			if (ele.getTagName().equalsIgnoreCase("userproperty")) {
    //				if (ele.getElementsByTagName("username").getLength()==0) {
    //					throw new Fault(new IllegalArgumentException("没有用户名,拦截器实施拦截"));
    //				}
    //				if (ele.getElementsByTagName("password").getLength()==0) {
    //					throw new Fault(new IllegalArgumentException("没有密码,拦截器实施拦截"));
    //				}
    //				String username = ele.getElementsByTagName("username").item(0).getNodeValue();
    //				String password = ele.getElementsByTagName("password").item(0).getNodeValue();
    //
    //				if(!username.equals("cxf")||!password.equals("123456")){
    //					throw new Fault(new IllegalArgumentException("用户名或者密码错误!"));
    //				}
    //			}
    //		}}}
    
  9.  Server端配置类
    package com.cxf.config;import com.cxf.interceptor.MyInterceptor;
    import com.cxf.webservice.HelloWorld;
    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 {@AutowiredBus bus;@AutowiredHelloWorld helloWorld;@Beanpublic Endpoint endpoint() {EndpointImpl endpoint = new EndpointImpl(bus, helloWorld);endpoint.getInInterceptors().add(new MyInterceptor());	// 添加自定义拦截器endpoint.publish("/HelloWorld");return endpoint;}
    }
  10.   Server端application.yml
    server:port: 8888servlet:context-path: /
  11. 启动Server端
    e2e7e9c4a7774285b1a7cf1bf195c397.png
  12.  Client端自动生成
    https://pan.baidu.com/s/1wTK2ly-SJgZM99TyAdmPiw?pwd=hbn1
    1.apache-cxf-3.1.5.zip解压后在环境变量添加bin路径2.执行命令:wsdl2java -encoding utf-8 -d C:\Users\Administrator\Desktop\wsdl http://localhost:8888/services/HelloWorld?wsdl3.将C:\Users\Administrator\Desktop\wsdl路径下自动生成的java文件复制到Client端

    ee37f3ad8ea543bea1e7658f8469a1b8.png

    57ac13a6de83415a887526766976f314.png

  13.  Client端pom.xml
    <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.java1234.webservice</groupId><artifactId>WS_Client</artifactId><version>0.0.1-SNAPSHOT</version><dependencies><!-- springboot webservice --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web-services</artifactId></dependency><!-- cxf webservice --><dependency><groupId>org.apache.cxf</groupId><artifactId>cxf-spring-boot-starter-jaxws</artifactId><version>3.2.14</version></dependency><!--JDK11需要添加此依赖--><dependency><groupId>com.sun.xml.ws</groupId><artifactId>jaxws-ri</artifactId><version>2.3.1</version></dependency></dependencies>
    </project>
  14.   Client端自定义拦截器(发送SOAP消息时调用)
    package com.cxf.interceptor;import java.util.List;import javax.xml.namespace.QName;import org.apache.cxf.binding.soap.SoapMessage;
    import org.apache.cxf.headers.Header;
    import org.apache.cxf.helpers.DOMUtils;
    import org.apache.cxf.interceptor.Fault;
    import org.apache.cxf.phase.AbstractPhaseInterceptor;
    import org.apache.cxf.phase.Phase;
    import org.w3c.dom.Document;
    import org.w3c.dom.Element;public class AddHeaderInterceptor extends AbstractPhaseInterceptor<SoapMessage> {private String userName;private String password;public AddHeaderInterceptor(String userName,String password) {super(Phase.PREPARE_SEND); // 准备发送SOAP消息的时候调用拦截器this.userName=userName;this.password=password;}/*** 客户端拦截器和服务端拦截器对应,客户端拦截器向SoapMessage添加的参数可以在服务端拦截器获取到并进行校验* 校验失败通过:throw new Fault(new IllegalArgumentException("没有Header,拦截器实施拦截"))抛出的异常在客户端控制台可见* @param message* @throws Fault*/public void handleMessage(SoapMessage message) throws Fault {List<Header> headerList=message.getHeaders();Document doc=DOMUtils.createDocument();Element ele=doc.createElement("authHeader");Element uElement=doc.createElement("userName");uElement.setTextContent(userName);Element pElement=doc.createElement("password");pElement.setTextContent(password);ele.appendChild(uElement);ele.appendChild(pElement);headerList.add(new Header(new QName("cxf"),ele));}}
    
  15. Client端测试类
    package com.cxf.webservice;import java.util.List;import com.cxf.interceptor.AddHeaderInterceptor;
    import com.cxf.webservice.impl.HelloWorldImplService;
    import org.apache.cxf.frontend.ClientProxy;
    import org.apache.cxf.interceptor.LoggingInInterceptor;
    import org.apache.cxf.interceptor.LoggingOutInterceptor;public class Client {public static void main(String[] args) {HelloWorldImplService service=new HelloWorldImplService();HelloWorld helloWorld = service.getHelloWorldImplPort();org.apache.cxf.endpoint.Client client=ClientProxy.getClient(helloWorld);client.getInInterceptors().add(new AddHeaderInterceptor("cxf","123456")); // 添加自定义拦截器client.getInInterceptors().add(new LoggingInInterceptor()); // 添加In拦截器 日志拦截器client.getOutInterceptors().add(new LoggingOutInterceptor()); // 添加Out拦截器 日志拦截器System.out.println(helloWorld.say("=========================="));List<Role> roles1=helloWorld.getRoleByUser(new User());for(Role role:roles1){System.out.println(role.getId()+","+role.getRoleName());}// 返回值为Map,服务端需要适配转换 @XmlJavaTypeAdapter(MapAdapter.class)-->Map<String, List<Role>> -> MyRole[]List<MyRole> roles2 = helloWorld.getRoles().item;for (MyRole myRole : roles2) {String key = myRole.getKey();List<Role> roles = myRole.getValue();System.out.println(key+":"+roles.toString());}}
    }
    

    8df56bfd75674d63a1401ea36f0c711d.png

  16.  彩蛋
    https://pan.baidu.com/s/1LrW4XRW71qB-ngeRgCMNHg?pwd=f68d
    客户端拦截器添加的参数在Server端拦截器获取失败,测试代码包点击上面链接下载,如果找到问题原因、解决办法、其他传参方式,请在评论区留言!

http://chatgpt.dhexx.cn/article/4GiD5Ncw.shtml

相关文章

走进cxf

一、什么是cxf 有很多人认为cxf就是webservice&#xff0c;其实cxf只是发布调用webservice的工具而已 Apache CXF Celtix Xfire&#xff0c;开始叫 Apache CeltiXfire&#xff0c;后来更名为 Apache CXF 了&#xff0c;以下简称为 CXF。Apache CXF 是一个开源的 web Service…

NewSQL ---- Mysql.8.0 与 MemSQL 7.0 大数据量查询性能对比

目录 1测试环境以及测试用例设计 1.1测试环境 1.2测试用例设计 2 千万级数据量性能测试对比 2.1 MemSQL时间范围分页查询 2.1.1 性能测试数据 2.2任务信息查询 2.2.1 性能测试数据 2.3 执行批次范围查询 2.3.1 性能测试数据 2.4 批次任务查询 2.4.1 性能测试数据 …

memsql架构2

接上次的MemSQL分布式架构介绍(一)&#xff0c;原文在这里&#xff1a;http://docs.memsql.com/latest/concepts/distributed_architecture/ 首先上张图&#xff0c;是我根据自己的理解画的&#xff0c;如有错误还请大家指出 几个概念 1、MemSQL有两种类型的表&#xff1a; ref…

MemSQL性能测试结果

1.查询的SQL select count(subie.user_id) as count from sum_user_basic_info_exp subie join sum_user_lend_info_exp sulie on sulie.user_idsubie.user_id where subie.curr_user_role_cd1 and subie.reg_dt >2016-08-29 and subie.reg_dt <2016-08-29 结…

【MySQL】SQL优化

SQL优化 1 插入数据 1.1 insert优化 如果我们需要一次性往数据库表中插入多条记录&#xff0c;可以从以下三个方面进行优化。 insert into tb_test values(1,tom); insert into tb_test values(2,cat); insert into tb_test values(3,jerry); .....1.批量插入数据 Insert…

MySQL慢SQL探究

文章目录 前言1、慢SQL捕获慢查询追踪配置方式 2、情况分析为什么查询会慢&#xff1f; 2.1 SQL执行计划分析explain执行计划分析PROFILE分析OPTIMIZER_TRACE分析 3、引擎参数配置分析I/O性能分析MySQL I/O参数 其他原因分析网络抖动单表数据量过大 总结 前言 我们在日常开发中…

【Mysql】SQL性能分析

【Mysql】SQL性能分析 文章目录 【Mysql】SQL性能分析1. SQL执行频率2. 慢查询日志3. profile详情4. explain 1. SQL执行频率 在控制台中通过命令 show [session|global] status 命令可以提供服务器状态信息。通过如下指令&#xff0c;可以查看当前数据库的 insert,update,del…

MemSQL可以为时间序列应用做些什么

版权声明&#xff1a;本文由腾讯云数据库产品团队整理&#xff0c;页面原始内容来自于db weekly英文官网&#xff0c;若转载请注明出处。翻译目的在于传递更多全球最新数据库领域相关信息&#xff0c;并不意味着腾讯云数据库产品团队赞同其观点或证实其内容的真实性。如果其他媒…

MySQL-SQL优化

文章目录 一、插入数据1、insert2、大批量插入数据 二、主键优化&#xff08;1&#xff09;数据组织方式&#xff08;2&#xff09;页分裂&#xff08;3&#xff09;页合并&#xff08;4&#xff09;索引设计原则 三、order by优化四、group by优化五、limit优化六、count优化1…

每秒1.28万亿行,最快的分布式关系数据库MemSQL又破记录了!

众所周知&#xff0c;如果交互式响应时间小于四分之一秒&#xff0c;那么人们会获得令人难以置信的满意度。当你提供的响应时间下降到大约四分之一秒时&#xff0c;交互对用户而言是即时的。 但是&#xff0c;由于大数据集和并发需求&#xff0c;给所有客户提供的速度水平似乎…

速度最快的数据库---MEMSQL的安装与部署

1. 什么是MEMSQL 前Facebook工程师创办的MemSQL公司获500万美元投资。号称世界上最快的分布式关系型数据库&#xff0c;兼容MySQL但快30倍&#xff0c;能实现每秒150万次事务。原理是仅用内存并将SQL预编译为C。2012年12月14&#xff0c;MemSQL 1.8 发布&#xff0c;号称最快的…

memsql-官宣世界最快的内存关系型数据库安装部署

官网地址&#xff1a;https://www.memsql.com/ 获取到的license:BGNhZmY4YjViM2Y1OTRhOTdiOTNlNTE0NmU3MGJhN2NlAAAAAAAAAAAEAAAAAAAAAAwwNAIYJLLETZcXn8NHKfJAS/Iai5hUjzaCMQ5PAhht2vDZAS1q1a49DPsq5gMGKY9AI0wmaSkAAA 1&#xff0c;memsql官网介绍 MemSQL 是一个分布式关系数…

memSQL简介

前言 由前Facebook工程师创办的MemSQL&#xff0c;号称世界上最快的分布式关系型数据库&#xff0c;兼容MySQL但快30倍&#xff0c;能实现每秒150万次事务。原理是仅用内存并将SQL预编译为C。 MemSQL 提供免费的开发者版本&#xff08;数据限制32G&#xff09;和全功能试用版…

统一异常处理解决方案

&#x1f481; 作者&#xff1a;小瓦匠 &#x1f496; 欢迎关注我的个人公众号&#xff1a;小瓦匠学编程。微信号&#xff1a;xiaowajiangxbc &#x1f4e2; 本中涉及到的所有代码资源&#xff0c;可以在公众号中获取&#xff0c;关注并回复&#xff1a;源码下载 &#x1f449;…

SpringBoot统一异常处理详解

文章目录 一、概述1、统一异常处理介绍2、原理和目标 二、Assert(断言)1、概述2、Assert自定义实战2.1 自定义接口Assert2.2 自定义异常2.3 Enum整合2.4 实战检测 三、统一异常处理器1、异常处理器说明1.1 handleServletException1.2 handleBindException和handleValidExceptio…

Shell 异常处理

原创&#xff1a;转载请注明出处 #!/bin/bash ##################服务器执行以下脚本############################# ## 重新上传脚本到服务器 -> 部署启动的脚本#当任何一行的命令执行错误的时候&#xff08;比如命令写错了&#xff09;直接退出&#xff0c;不继续往下执行…

java中的统一异常处理

目录 统一异常处理的原因 如果进行统一异常处理 1、编写统一异常处理类与方法 2、编写自定义异常类 3、定义异常枚举类 4、抛出指定异常 小提醒 统一异常处理的原因 在我们写代码的时候&#xff0c;因为各种场景需要进行各种校验&#xff0c;我们就可能会进行多种响应&…

JNI异常处理

前言 本文所要介绍的异常处理是指通过JNI调用java层方法时产生的异常处理&#xff0c;并不是指JNI调用Native层函数时产生的异常处理&#xff0c;如果童鞋们想要了解Native层的异常处理可以参考笔者之前的文章《C之异常处理》 按照java的经验&#xff0c;当发生异常而又没有捕…

Python——异常处理

文章目录 异常Python中的异常类捕获与处理异常自定义异常类with语句断言 异常 异常是在程序执行过程中发生的影响程序正常执行的一个事件。异常是Python对象&#xff0c;当Python无法正常处理程序时就会抛出一个异常。一旦Python脚本发生异常&#xff0c;程序需要捕获并处理它…

python异常处理输入不是整数_Python异常处理

异常处理: Python程序运行语法出错会有异常抛出不处理异常会导致程序终止 示例:用户输入一个整数转换成int型,如果用户输入的不是数字而是其他例如字母等则会出现异常 不使用异常处理代码的处理方法 #cat 异常处理.py abc = input("请输入一个数字") if not ab…