本示例引用的包为cxf-rt-frontend-jaxws-3.1.15.jar
maven引用
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-core</artifactId>
<version>3.1.15</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<version>3.1.15</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http-jetty</artifactId>
<version>3.1.15</version>
</dependency>
第一步首先创建需要发布的接口
/**
* @ClassName IUncallWorld
* @Description service发布用测试接口
* @author weiw
* @date 2018年4月3日
*
*/
@WebService
public interface CallWorldService {
/**
*
* @Title: callWorld
* @Description: 测试接口
* @param text
* @return 参数说明
* @return String 返回类型
*/
String callWorld(@WebParam(name = "text") String text);
}
第二步 创建类实现接口
public class CallWordServiceImpl implements CallWorldService {
@Override
public String callWorld(String text) {
System.out.println("进入服务器方法!参数为:" + text);
String word = "<?xml version='1.0' encoding='utf-8'?><uncall><UncallWorld><Response>UncallWorld:" + text
+ "</Response></UncallWorld></uncall>";
return word;
}
}
第三步 创建发布方法
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.cxf.jaxws.JaxWsServerFactoryBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.common.PropertyLoader;
import com.service.CallWorldService;
import com.service.ServiceConfig;
import com.service.impl.CallWordServiceImpl;
public class Server implements ServletContextListener {
public static void serverStart() throws Exception {
CallWorldService callWorld = new CallWordServiceImpl();
JaxWsServerFactoryBean factory = new JaxWsServerFactoryBean();
//放入服务端接口 (第一步的接口)
factory.setServiceClass(CallWorldService.class);
//放入设置的url地址 (自己设置的url:webServiceIP)
factory.setAddress("http://127.0.0.1:8888/test");
//放入服务对象 (第二步的实现类)
factory.setServiceBean(callWorld);
//创建webservice服务
factory.create();
logger.info("\n已开启服务>>>>>>>>>>>>\nwebUrl:{}",webServiceIP);
}
}
最后写个main方法调用serverStart() 方法就OK了;简单的三步发布网络服务!
客户端编写:
public static void main(String[] arges){
String wsUrl="http://127.0.0.1:8888/test";
CallWorldService callWorldService = getProxyService(wsUrl,CallWorldService.class);
callWorldService.callWorld("test");
}
public static <T> T getProxyService(String url,Class<T> serviceClass){
JaxwsProxyFactotoryBean proxyFactotory = new JaxwsProxyFactotoryBean();
proxyFactotory.setAddress(url);
return proxyFactotory.create(serviceClass);
}