SpringBoot整合CXF实现WebService

简介: SpringBoot整合CXF实现WebService

pom依赖:

 <parent>
    <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-parent</artifactId>
     <version>2.2.4.RELEASE</version>
     <relativePath/> <!-- lookup parent from repository -->
 </parent>
 <!--webservice-->
<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-web-services</artifactId>
 </dependency>
 <dependency>
     <groupId>org.apache.cxf</groupId>
     <artifactId>cxf-rt-frontend-jaxws</artifactId>
     <version>3.1.6</version>
 </dependency>
 <dependency>
     <groupId>org.apache.cxf</groupId>
     <artifactId>cxf-rt-transports-http</artifactId>
     <version>3.1.6</version>
 </dependency>

【1】服务端

需要注意的是方法参数与返回结果不要使用泛型,如果可以请尽量使用String并自己对参数进行格式化转换!


① UserWebService

定义service接口

import javax.jws.WebService;
@WebService(name = "UserWebService", // 暴露服务名称
        targetNamespace = "http://cxf.webservice.com"// 命名空间,一般是接口的包名倒序
)
public interface UserWebService {
    //根据ID获取用户信息
    String getUserById(Long id);
    //更新用户信息,参数为json格式
    String updateUser(String updateUser);
}

② UserWebServiceImpl

定义service服务实现类,这里服务实现userMapper采用的mybatis。

@WebService(serviceName = "UserWebService", // 与接口中指定的name一致
        targetNamespace = "http://cxf.webservice.com", // 与接口中的命名空间一致,一般是接口的包名倒
        endpointInterface = "com.webservice.cxf.UserWebService"// 接口地址
)
public class UserWebServiceImpl implements  UserWebService {
    @Autowired
    SysUserMapper userMapper;
    @Override
    public String getUserById(Long id) {
        return JSON.toJSONString(ResultUtil.successData(userMapper.selectById(id)));
    }
    @Override
    public String updateUser(String user) {
        JSONObject object = JSONObject.parseObject(user);
        SysUser sysUser = object.toJavaObject(SysUser.class);
        userMapper.updateById(sysUser);
        return JSON.toJSONString(ResultUtil.successData(userMapper.selectById(sysUser.getId())));
    }
}

③ CXF配置类

@Configuration
public class CxfConfig {
    @Bean
    public ServletRegistrationBean cxfServlet() {
        return new ServletRegistrationBean(new CXFServlet(),"/userWebService/*");
    }
    @Bean(name = Bus.DEFAULT_BUS_ID)
    public SpringBus springBus() {
        return new SpringBus();
    }
    @Bean
    public UserWebServiceImpl userWebService() {
        return new UserWebServiceImpl();
    }
    @Bean
    public Endpoint endpoint() {
        EndpointImpl endpoint = new EndpointImpl(springBus(), userWebService());
        endpoint.publish("/api");
        return endpoint;
    }
}


【2】动态客户端实例测试

这里不生成客户端代码而是使用JaxWsDynamicClientFactory.newInstance()来进行测试。

@Test
public void getUserById(){
     //创建动态客户端
     JaxWsDynamicClientFactory factory = JaxWsDynamicClientFactory.newInstance();
     Client client = factory.createClient("http://localhost:8086/userWebService/api?wsdl");
     // 需要密码的情况需要加上用户名和密码 
     //client.getOutInterceptors().add(new ClientLoginInterceptor(USER_NAME,PASS_WORD));
     HTTPConduit conduit = (HTTPConduit) client.getConduit();
     HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
     httpClientPolicy.setConnectionTimeout(2000);  //连接超时
     httpClientPolicy.setAllowChunking(false);    //取消块编码
     httpClientPolicy.setReceiveTimeout(120000);     //响应超时
     conduit.setClient(httpClientPolicy);
     //client.getOutInterceptors().addAll(interceptors);//设置拦截器
     try{
         Object[] objects = new Object[0];
         // invoke("方法名",参数1,参数2,参数3....);
         objects = client.invoke("getUserById", 1L);
         logger.info("-------------------------------------------------------");
         logger.info("返回数据:" + objects[0]);
     }catch (Exception e){
         e.printStackTrace();
     }
 }

如果需要用户名、密码校验可以添加ClientLoginInterceptor拦截器。


【3】生成客户端代码

在idea中进入File > New Project…菜单打开新建项目窗口,依次选择Java、WebServices Client,Version项选择Apache Axis,Libraries项选择 Download。然后点击Next按钮进入下一页。


生成代码然后在新窗口打开工程,会出现如下图:

如果没有弹出上面窗口,则手动创建。工程名右键选择WebServices > Generate Java Code From Wsdl ,生成客户端代码。


生成的代码如下,此时是不可用的:

修改代码如下:

public class HelloWorldClient {
  public static void main(String[] argv) {
      try {
          UserWebService_ServiceLocator locator = new UserWebService_ServiceLocator();
          UserWebService_PortType userWebServiceImplPort = locator.getUserWebServiceImplPort();
          String userById = userWebServiceImplPort.getUserById(1L);
          System.out.println(userById);
      } catch (javax.xml.rpc.ServiceException ex) {
          ex.printStackTrace();
      } catch (java.rmi.RemoteException ex) {
          ex.printStackTrace();
      }  
  }
}

测试结果如下图:

目录
相关文章
|
6月前
【Azure 应用服务】Web App Service 中的 应用程序配置(Application Setting) 怎么获取key vault中的值
【Azure 应用服务】Web App Service 中的 应用程序配置(Application Setting) 怎么获取key vault中的值
|
3月前
【Azure App Service】PowerShell脚本批量添加IP地址到Web App允许访问IP列表中
Web App取消公网访问后,只允许特定IP能访问Web App。需要写一下段PowerShell脚本,批量添加IP到Web App的允许访问IP列表里!
|
6月前
|
关系型数据库 MySQL Linux
【Azure 应用服务】在创建Web App Service的时候,选Linux系统后无法使用Mysql in App
【Azure 应用服务】在创建Web App Service的时候,选Linux系统后无法使用Mysql in App
【Azure 应用服务】在创建Web App Service的时候,选Linux系统后无法使用Mysql in App
|
6月前
|
Shell PHP Windows
【Azure App Service】Web Job 报错 UNC paths are not supported. Defaulting to Windows directory.
【Azure App Service】Web Job 报错 UNC paths are not supported. Defaulting to Windows directory.
|
6月前
|
Linux 应用服务中间件 网络安全
【Azure 应用服务】查看App Service for Linux上部署PHP 7.4 和 8.0时,所使用的WEB服务器是什么?
【Azure 应用服务】查看App Service for Linux上部署PHP 7.4 和 8.0时,所使用的WEB服务器是什么?
|
6月前
【Azure 应用服务】通过 Web.config 开启 dotnet 应用的 stdoutLog 日志,查看App Service 产生500错误的原因
【Azure 应用服务】通过 Web.config 开启 dotnet 应用的 stdoutLog 日志,查看App Service 产生500错误的原因
|
6月前
|
Linux Python
【Azure 应用服务】Azure App Service For Linux 上实现 Python Flask Web Socket 项目 Http/Https
【Azure 应用服务】Azure App Service For Linux 上实现 Python Flask Web Socket 项目 Http/Https
|
6月前
|
存储 安全 网络安全
【Azure 环境】使用Azure中的App Service部署Web应用,以Windows为主机系统是否可以启动防病毒,防恶意软件服务呢(Microsoft Antimalware)?
【Azure 环境】使用Azure中的App Service部署Web应用,以Windows为主机系统是否可以启动防病毒,防恶意软件服务呢(Microsoft Antimalware)?
|
6月前
|
存储 Linux 网络安全
【Azure 应用服务】App Service For Linux 如何在 Web 应用实例上住抓取网络日志
【Azure 应用服务】App Service For Linux 如何在 Web 应用实例上住抓取网络日志
|
6月前
【Azure 云服务】Azure Cloud Service 为 Web Role(IIS Host)增加自定义字段 (把HTTP Request Header中的User-Agent字段增加到IIS输出日志中)
【Azure 云服务】Azure Cloud Service 为 Web Role(IIS Host)增加自定义字段 (把HTTP Request Header中的User-Agent字段增加到IIS输出日志中)

热门文章

最新文章

  • 1
    打造高效的Web Scraper:Python与Selenium的完美结合
    13
  • 2
    Burp Suite Professional 2025.2 (macOS, Linux, Windows) - Web 应用安全、测试和扫描
    26
  • 3
    AppSpider Pro 7.5.015 for Windows - Web 应用程序安全测试
    20
  • 4
    【02】客户端服务端C语言-go语言-web端PHP语言整合内容发布-优雅草网络设备监控系统-2月12日优雅草简化Centos stream8安装zabbix7教程-本搭建教程非docker搭建教程-优雅草solution
    54
  • 5
    部署使用 CHAT-NEXT-WEB 基于 Deepseek
    342
  • 6
    【2025优雅草开源计划进行中01】-针对web前端开发初学者使用-优雅草科技官网-纯静态页面html+css+JavaScript可直接下载使用-开源-首页为优雅草吴银满工程师原创-优雅草卓伊凡发布
    26
  • 7
    java spring 项目若依框架启动失败,启动不了服务提示端口8080占用escription: Web server failed to start. Port 8080 was already in use. Action: Identify and stop the process that’s listening on port 8080 or configure this application to listen on another port-优雅草卓伊凡解决方案
    40
  • 8
    零基础构建开源项目OpenIM桌面应用和pc web- Electron篇
    28
  • 9
    【01】客户端服务端C语言-go语言-web端PHP语言整合内容发布-优雅草网络设备监控系统-硬件设备实时监控系统运营版发布-本产品基于企业级开源项目Zabbix深度二开-分步骤实现预计10篇合集-自营版
    22
  • 10
    FastAPI与Selenium:打造高效的Web数据抓取服务 —— 采集Pixabay中的图片及相关信息
    55