(一)CXF之发布第一个WebService服务

一、CXF入门

  1.1  前提

  • Apache CXF 是一个开源的 Services 框架,CXF 帮助您利用 Frontend 编程 API 来构建和开发 Services ,像 JAX-WS 。这些 Services 可以支持多种协议,比如:SOAP、XML/HTTP、RESTful HTTP 或者 CORBA ,并且可以在多种传输协议上运行,比如:HTTP、JMS 或者 JBI,CXF 大大简化了 Services 的创建,同时它继承了 XFire 传统,一样可以天然地和 Spring 进行无缝集成。
  • 关于webService的基础知识,请查看本人的webService的系列教程
  • 建议先学本人的webService的系列教程在来学习CXF系列教程
  • 建议都使用jdk1.8以上

  1.2  需求

  • 用CXF发布WebService服务

  1.3  案例

  • 引入依赖,本文使用5.1.3版本的CXF
    <dependencies>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-frontend-jaxws</artifactId>
            <version>3.1.5</version>
        </dependency>

        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-core</artifactId>
            <version>3.1.5</version>
        </dependency>

        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-transports-http-jetty</artifactId>
            <version>3.1.5</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.0</version>
            <scope>provided</scope>
        </dependency>
        
    </dependencies>
  • 编写服务接口

package com.shyroke.service;

import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;

@WebService
public interface IFirstService {

    @WebResult(name="addResult")
    public int  add(@WebParam(name="x")int x,@WebParam(name="y")int y);
}
  • 编写服务实现类

package com.shyroke.service;

import javax.jws.WebService;

@WebService(endpointInterface="com.shyroke.service.IFirstService")
public class FirstServiceImpl implements IFirstService {

    public int add(int x, int y) {
        
        return x+y;
    }

}
  • 发布服务

package com.shyroke.publish;


import org.apache.cxf.jaxws.JaxWsServerFactoryBean;

import com.shyroke.service.FirstServiceImpl;
import com.shyroke.service.IFirstService;

public class PublishMain {
    public static void main(String[] args) {
        
        String address="http://localhost:1234/first";
        JaxWsServerFactoryBean factoryBean=new JaxWsServerFactoryBean();
        factoryBean.setAddress(address);
        factoryBean.setServiceClass(IFirstService.class);
        factoryBean.setServiceBean(new FirstServiceImpl());
        
        factoryBean.create();
        System.out.println("服务发布.......");
        
    }
}

结果:

原文地址:https://www.cnblogs.com/shyroke/p/7944546.html