Spring Boot+CXF搭建WebService(转)
概述
最近项目用到在Spring boot下搭建WebService服务,对Java语言下的WebService了解甚少,而今抽个时间查阅资料整理下Spring Boot结合CXF打架WebService一般步骤与方法;本文章结合各个博客资料整理而成,如有雷同,谨记转载;
Spring Boot WebService开发
需要依赖Maven的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.</modelVersion>
<groupId>com.dbgo</groupId>
<artifactId>webservicedemo</artifactId>
<version>0.0.-SNAPSHOT</version>
<packaging>jar</packaging>
<name>webservicedemo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5..RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--WerbService CXF依赖-->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<version>3.1.</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
<version>3.1.</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency> <dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
</dependencies> <build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
构建并发布服务
构建Model对象
package com.dbgo.webservicedemo.Model; import java.io.Serializable;
import java.util.Date; public class User implements Serializable {
private static final long serialVersionUID = -5939599230753662529L;
private String userId;
private String username;
private String age;
private Date updateTime; public String getUserId() {
return userId;
} public void setUserId(String userId) {
this.userId = userId;
} public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} public String getAge() {
return age;
} public void setAge(String age) {
this.age = age;
} public Date getUpdateTime() {
return updateTime;
} public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
}
构建服务接口
package com.dbgo.webservicedemo.service; import com.dbgo.webservicedemo.Model.User; import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import java.util.ArrayList; @WebService
public interface UserService {
@WebMethod
String getName(@WebParam(name = "userId") String userId); @WebMethod
User getUser(String userI); @WebMethod
ArrayList<User> getAlLUser();
}
构建接口实现类
package com.dbgo.webservicedemo.service; import com.dbgo.webservicedemo.Model.User; import javax.jws.WebService;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map; @WebService(targetNamespace="http://service.webservicedemo.dbgo.com/",endpointInterface = "com.dbgo.webservicedemo.service.UserService")
public class UserServiceImpl implements UserService {
private Map<String, User> userMap = new HashMap<String, User>();
public UserServiceImpl() {
System.out.println("向实体类插入数据");
User user = new User();
user.setUserId("");
user.setUsername("zhansan");
user.setAge("");
user.setUpdateTime(new Date());
userMap.put(user.getUserId(), user); user = new User();
user.setUserId("");
user.setUsername("lisi");
user.setAge("");
user.setUpdateTime(new Date());
userMap.put(user.getUserId(), user); user = new User();
user.setUserId("");
user.setUsername("wangwu");
user.setAge("");
user.setUpdateTime(new Date());
userMap.put(user.getUserId(), user);
}
@Override
public String getName(String userId) {
return "liyd-" + userId;
}
@Override
public User getUser(String userId) {
User user= userMap.get(userId);
return user;
} @Override
public ArrayList<User> getAlLUser() {
ArrayList<User> users=new ArrayList<>();
userMap.forEach((key,value)->{users.add(value);});
return users;
}
}
备注说明:接口实现类名称前的注解targetNamespace是当前类实现接口所在包名称的反序(PS:加上反斜线),endpointInterface是当前需要实现接口的全称;@WebService(targetNamespace="http://service.webservicedemo.dbgo.com/",endpointInterface = "com.dbgo.webservicedemo.service.UserService")
服务发布类编写
package com.dbgo.webservicedemo; import com.dbgo.webservicedemo.service.UserService;
import com.dbgo.webservicedemo.service.UserServiceImpl;
import org.apache.cxf.Bus;
import org.apache.cxf.bus.spring.SpringBus;
import org.apache.cxf.jaxws.EndpointImpl;
import org.apache.cxf.transport.servlet.CXFServlet;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import javax.xml.ws.Endpoint; @Configuration
public class WebServiceConfig { @Bean
public ServletRegistrationBean dispatcherServlet(){
return new ServletRegistrationBean(new CXFServlet(),"/service/*");//发布服务名称
} @Bean(name = Bus.DEFAULT_BUS_ID)
public SpringBus springBus()
{
return new SpringBus();
} @Bean
public UserService userService()
{
return new UserServiceImpl();
} @Bean
public Endpoint endpoint() {
EndpointImpl endpoint=new EndpointImpl(springBus(), userService());//绑定要发布的服务
endpoint.publish("/user"); //显示要发布的名称
return endpoint;
}
}
运行程序,输入 http://localhost:8080/service/user?wsdl 即可查询发布出去的接口文件;
如果需要发布多个webservice,需要配置多个Config实现类文件;
客户端调用服务
基于cxf客户端调用WebService可以简单概述2中模式:动态调用和协议调用;
package com.dbgo.webservicedemo; import com.dbgo.webservicedemo.Model.User;
import com.dbgo.webservicedemo.service.UserService;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.frontend.ClientProxy;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.apache.cxf.transport.http.HTTPConduit;
import org.apache.cxf.transports.http.configuration.HTTPClientPolicy; import java.util.ArrayList; public class webserviceclient { //动态调用
public static void main(String[] args) throws Exception {
JaxWsDynamicClientFactory dcflient=JaxWsDynamicClientFactory.newInstance(); Client client=dcflient.createClient("http://localhost:8080/service/user?wsdl"); Object[] objects=client.invoke("getUser","");
System.out.println("*******"+objects[].toString()); Object[] objectall=client.invoke("getAlLUser");
System.out.println("*******"+objectall[].toString()); main3(args);
} //调用方式二,通过接口协议获取数据类型
public static void main2(String[] args) throws Exception {
JaxWsProxyFactoryBean jaxWsProxyFactoryBean=new JaxWsProxyFactoryBean();
jaxWsProxyFactoryBean.setAddress("http://localhost:8080/service/user?wsdl");
jaxWsProxyFactoryBean.setServiceClass(UserService.class); UserService userService=(UserService)jaxWsProxyFactoryBean.create();
User userResult= userService.getUser("");
System.out.println("UserName:"+userResult.getUsername());
ArrayList<User> users=userService.getAlLUser(); } //调用方式三,通过接口协议获取数据类型,设置链接超时和响应时间
public static void main3(String[] args) throws Exception {
JaxWsProxyFactoryBean jaxWsProxyFactoryBean=new JaxWsProxyFactoryBean();
jaxWsProxyFactoryBean.setAddress("http://localhost:8080/service/user?wsdl");
jaxWsProxyFactoryBean.setServiceClass(UserService.class); UserService userService = (UserService) jaxWsProxyFactoryBean.create(); // 创建客户端对象
Client proxy= ClientProxy.getClient(userService);
HTTPConduit conduit=(HTTPConduit)proxy.getConduit();
HTTPClientPolicy policy=new HTTPClientPolicy();
policy.setConnectionTimeout();
policy.setReceiveTimeout();
conduit.setClient(policy); User userResult= userService.getUser("");
System.out.println("UserName:"+userResult.getUsername());
ArrayList<User> users=userService.getAlLUser(); }
}
基于wsimport和JAX-WS调用Web Service接口
使用Jdk原生态wsimport指令生成相应的接口文件,来调取webservice接口。操作如下:
1、生成接口文件:cmd->wsimport -d . -s . -p acme.client http://127.0.0.1/Services/InvoiceService.asmx?WSDL
即可通过cmd命令生成相应的接口文件;
参数说明:
-d 指定生成输出文件的保存路径(.class文件,根据需要决定是否生成class文件)
-s 指定生成的java源文件的保存路径(.java文件,根据需要决定是否生成java源文件)
-p 指定生成的java类的包(package)名称
http://127.0.0.1/Services/InvoiceService.asmx?WSDL URL地址,URL地址后面必须添加“?WSDL”参数。WSDL参数也可以是小写(wsdl)。
2、配置调用相应的文件
import java.net.MalformedURLException;
import java.net.URL; import javax.xml.namespace.QName; import com.opertion.wsimport.HiService; /**
* 使用Service类进行调用
* @author Administrator
*/
public class Service {
public static void main(String[] args) throws MalformedURLException {
//wsdl网络路径
URL url = new URL("http://127.0.0.1/Services/InvoiceService.asmx?WSDL");
//服务描述中服务端点的限定名称 两个参数分别为 命名空间 服务名
QName qName = new QName("http://tempuri.org/", "InvoiceService");
//创建服务对象
javax.xml.ws.Service service = javax.xml.ws.Service.create(url, qName);
//获得Hiservice的实现类对象
InvoiceService hiService = service.getPort(new QName("http://tempuri.org/","InvoiceServiceSoap"),InvoiceService.class);
//调用WebService方法
System.out.println(hiService.sayHi("xiaoming"));
}
}
注意事项:
命名空间 (http://tempuri.org/)的取值,是如下内容:

服务名称InvoiceService和InvoiceServiceSoap的取值:

参考博客
Spring boot+CXF开发WebService Demo https://www.cnblogs.com/fuxin41/p/6289162.html
springboot1.5.4 集成cxf完整实例 https://www.cnblogs.com/xiaojf/p/7231529.html
JAX-WS调用Web Service参考地址
通过javax.xml.ws.Service的方式调用WebService https://blog.csdn.net/syy19930112/article/details/17427165
使用wsimport和JAX-WS调用Web Service接口 https://www.cnblogs.com/yitouniu/p/7640079.html#commentform
Spring Boot+CXF搭建WebService(转)的更多相关文章
- Spring Boot+CXF搭建WebService
Spring Boot WebService开发 需要依赖Maven的Pom清单 <?xml version="1.0" encoding="UTF-8" ...
- Spring Boot+CXF搭建WebService服务参考资料
pom.xml文件引入包: <!--WerbService CXF依赖--> <dependency> <groupId>org.apache.cxf</gr ...
- Spring boot+CXF开发WebService
最近工作中需要用到webservice,而且结合spring boot进行开发,参照了一些网上的资料,配置过程中出现的了一些问题,于是写了这篇博客,记录一下我这次spring boot+cxf开发的w ...
- Spring boot+CXF开发WebService Demo
最近工作中需要用到webservice,而且结合spring boot进行开发,参照了一些网上的资料,配置过程中出现的了一些问题,于是写了这篇博客,记录一下我这次spring boot+cxf开发的w ...
- struts1+spring+myeclipse +cxf 开发webservice以及普通java应用调用webservice的实例
Cxf + Spring+ myeclipse+ cxf 进行 Webservice服务端开发 使用Cxf开发webservice的服务端项目结构 Spring配置文件applicationCont ...
- Spring Boot 项目学习 (三) Spring Boot + Redis 搭建
0 引言 本文主要介绍 Spring Boot 中 Redis 的配置和基本使用. 1 配置 Redis 1. 修改pom.xml,添加Redis依赖 <!-- Spring Boot Redi ...
- Spring boot项目搭建及简单实例
Spring boot项目搭建 Spring Boot 概述 Build Anything with Spring Boot:Spring Boot is the starting point for ...
- spring boot+mybatis搭建项目
一.创建spring boot项目 1.File->New->Project 2.选择 Spring Initializr ,然后选择默认的 url 点击[Next]: 3.修改项目信息 ...
- Spring集成CXF发布WebService并在客户端调用
Spring集成CXF发布WebService 1.导入jar包 因为官方下载的包里面有其他版本的sprring包,全导入会产生版本冲突,所以去掉spring的部分,然后在项目根目录下新建了一个CXF ...
随机推荐
- red()、redinle()、redlines()三者之间的关系
# 关于read()方法: # 1.读取整个文件,将文件内容放到一个字符串变量中 # 2.如果文件大于可用内存,不可能使用这种处理 file_object = open("a.txt&quo ...
- mysql-python安装时EnvironmentError: mysql_config not found
mysql-python安装时EnvironmentError: mysql_config not found 在安装 mysql-python时,会出现: 复制代码 sh: mysql_config ...
- CSS当中数学表达式calc
CSS当中数学表达式calc 数学表达式calc()是CSS中的函数,主要用于数学运算.使用calc()为页面元素布局提供了便利和新的思路.本文将介绍calc()的相关内容 定义 数学表达式calc ...
- Hdoj 1425.sort 题解
Problem Description 给你n个整数,请按从大到小的顺序输出其中前m大的数. Input 每组测试数据有两行,第一行有两个数n,m(0<n,m<1000000),第二行包含 ...
- [问题]Android listView item edittext 不能调用软键盘输入法
android listview item edittext not softkeyboard edittext可以获取焦点, 可以触发事件, 但是就是不能调用输入法, 不知道为什么? 难道不能在i ...
- Vue(项目踩坑)_解决vue中axios请求跨域的问题
一.前言 今天在做项目的时候发现axios不能请求跨域接口 二.主要内容 1.之前直接用get方式请求聚合数据里的接口报错如下 2.当前请求的代码 3.解决方法 (1)在项目目录中依次找到:confi ...
- 从线程池到synchronized关键字详解
线程池 BlockingQueue synchronized volatile 前段时间看了一篇关于"一名3年工作经验的程序员应该具备的技能"文章,倍受打击.很多熟悉而又陌生的知识 ...
- 常见Web攻击
一.SQL注入 1. sql注入的危害 非法读取.篡改.删除数据库中的数据 盗取用户的各类敏感信息,获取利益 通过修改数据库来修改网页上的内容 注入木马等 2. 实例 MYSQLDB # 通过在用户名 ...
- 在Mac下安装mongodb
本来想用brew一键安装的,但是一直不成功,解决了一个问题随即又抛出一个问题,后来只好老老实实去官网下载安装包了,解压到/usr/local目录下. 之前下载压缩包时忘记下载到/usr/local目录 ...
- 静态IP设置
先查看自动网络的ip地址,然后设置 cmd进入DOS输入命令:ipconfig /all 设置固定IP