杰瑞科技汇

Java开发WebService接口,如何快速实现?

  1. JAX-WS (Java API for XML Web Services):这是 Java 官方推出的、比较传统的 WebService 规范,它使用标准的 SOAP (Simple Object Access Protocol) 协议进行通信,通常与 WSDL (Web Services Description Language) 文件紧密绑定。Spring Boot 默认不集成 JAX-WS,但可以轻松整合。
  2. Spring Boot Starter Web Services:这是 Spring 框架对 JAX-WS 的封装,使其更易于在 Spring 生态中使用。
  3. Spring Boot with RESTful(目前最主流的方式) 虽然严格来说,基于 RESTful 风格的 API 通常不被归类为 "WebService"(因为它们不使用 SOAP/WSDL),但在现代开发中,当开发者说 "用 Java 开发 WebService 接口" 时,绝大多数情况下指的是开发 RESTful API,它使用 HTTP 协议,数据格式通常是 JSON,更轻量、更易于与前端和移动端集成。

我将为你分别介绍这三种方式,并重点突出当前最常用的 RESTful API 开发方法。

Java开发WebService接口,如何快速实现?-图1
(图片来源网络,侵删)

使用 JAX-WS (传统方式)

这种方式比较底层,通常用于需要严格遵循 SOAP 协议和 WSDL 规范的企业级应用中。

创建 Maven 项目

pom.xml 中添加 JAX-WS 的依赖:

<dependencies>
    <!-- JAX-WS API -->
    <dependency>
        <groupId>javax.xml.ws</groupId>
        <artifactId>jaxws-api</artifactId>
        <version>2.3.1</version>
    </dependency>
    <!-- JAX-WS RI (Reference Implementation) -->
    <dependency>
        <groupId>com.sun.xml.ws</groupId>
        <artifactId>jaxws-rt</artifactId>
        <version>2.3.3</version>
    </dependency>
</dependencies>

创建服务接口和实现类

步骤:

  1. 定义一个标准的 Java 接口,使用 @WebService 注解标记。
  2. 创建一个实现类,实现该接口。
  3. 在实现类上使用 @WebService(endpointInterface = "你的接口全限定名") 来指定它实现了哪个接口。

接口 HelloWorld.java

Java开发WebService接口,如何快速实现?-图2
(图片来源网络,侵删)
import javax.jws.WebService;
import javax.jws.WebMethod;
// @WebService 注解将此接口声明为一个 WebService
@WebService
public interface HelloWorld {
    // @WebMethod 注解将此方法暴露为 WebService 的一个操作
    @WebMethod
    String sayHello(String name);
}

实现类 HelloWorldImpl.java

import javax.jws.WebService;
// @WebService 注解指定这个类是哪个接口的实现
@WebService(endpointInterface = "com.example.webservice.jaxws.HelloWorld")
public class HelloWorldImpl implements HelloWorld {
    @Override
    public String sayHello(String name) {
        return "Hello, " + name + "! Welcome to JAX-WS.";
    }
}

发布 WebService

你可以编写一个 main 方法来发布这个服务,服务默认会在一个内嵌的 HTTP 服务器上运行。

import javax.xml.ws.Endpoint;
public class HelloWorldPublisher {
    public static void main(String[] args) {
        // 定义服务的访问地址
        String address = "http://localhost:8888/ws/hello";
        // 发布服务
        Endpoint.publish(address, new HelloWorldImpl());
        System.out.println("WebService is published at: " + address);
    }
}

测试

运行 HelloWorldPublishermain 方法,你可以通过浏览器访问 http://localhost:8888/ws/hello?wsdl,如果看到一个 XML 文件(WSDL 文件),说明服务发布成功。

你可以使用工具如 SoapUI 来调用这个服务。

Java开发WebService接口,如何快速实现?-图3
(图片来源网络,侵删)

使用 Spring Boot 整合 JAX-WS

这种方式结合了 Spring 的依赖注入和生命周期管理,比纯 JAX-WS 更优雅。

创建 Spring Boot 项目

pom.xml 中添加 spring-boot-starter-web-services 依赖。

<dependencies>
    <!-- Spring Boot Web Services for JAX-WS -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web-services</artifactId>
    </dependency>
    <!-- Spring Boot Test -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

创建服务接口和实现类

这里的接口和实现类与方式一完全相同。

接口 HelloWorld.java

import javax.jws.WebService;
import javax.jws.WebMethod;
@WebService
public interface HelloWorld {
    @WebMethod
    String sayHello(String name);
}

实现类 HelloWorldImpl.java

import javax.jws.WebService;
// 使用 @Component 让 Spring 管理这个 Bean
@Component
@WebService(serviceName = "HelloWorld", // 指定 WSDL 中的服务名
            endpointInterface = "com.example.webservice.springws.HelloWorld",
            targetNamespace = "http://springws.example.com/") // 指定命名空间
public class HelloWorldImpl implements HelloWorld {
    @Override
    public String sayHello(String name) {
        return "Hello, " + name + "! Welcome to Spring JAX-WS.";
    }
}

配置和发布服务

Spring Boot 会自动扫描并发布带有 @WebService 注解的 Bean,你只需要在配置类中启用即可。

主应用类 JaxWsApplication.java

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.webservices.client.WebServiceTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.ws.config.annotation.EnableWs;
import org.springframework.ws.config.annotation.WsConfigurerAdapter;
import org.springframework.ws.server.EndpointMapping;
import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;
import org.springframework.ws.server.endpoint.annotation.RequestPayload;
import org.springframework.ws.server.endpoint.annotation.ResponsePayload;
// 启用 Spring Web Services 支持
@EnableWs
@SpringBootApplication
public class JaxWsApplication {
    public static void main(String[] args) {
        SpringApplication.run(JaxWsApplication.class, args);
    }
    // 如果你需要更精细的控制,可以配置 EndpointMapping
    // 但通常不需要,Spring Boot 会自动处理
}

测试

启动 Spring Boot 应用,服务默认会发布在 http://localhost:8080/services 路径下,你可以通过访问 http://localhost:8080/services/helloWorld?wsdl (注意 helloWorld 是实现类名首字母小写) 来查看 WSDL 文件。


使用 Spring Boot 开发 RESTful API (最主流)

这是目前最流行、最推荐的方式,它不使用 SOAP,而是基于 HTTP 协议,数据格式通常是 JSON。

创建 Spring Boot 项目

使用 Spring Initializr (https://start.spring.io/) 创建项目,选择以下依赖:

  • Spring Web: 用于构建 RESTful 应用。

生成的 pom.xml 会自动包含 spring-boot-starter-web

创建 Controller

Controller 用于处理 HTTP 请求,我们使用 @RestController 注解,它会自动将方法的返回值转换为 JSON 格式。

HelloController.java

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
// @RestController = @Controller + @ResponseBody
@RestController
// @RequestMapping 定义一个基础路径
@RequestMapping("/api")
public class HelloController {
    // @GetMapping 映射 HTTP GET 请求
    // @PathVariable 用于从 URL 路径中获取变量
    @GetMapping("/hello/{name}")
    public String sayHello(@PathVariable String name) {
        return "Hello, " + name + "! Welcome to Spring Boot RESTful API.";
    }
    // 也可以返回一个复杂的对象
    @GetMapping("/user/{name}")
    public User getUser(@PathVariable String name) {
        User user = new User();
        user.setName(name);
        user.setAge(30);
        return user;
    }
}
// 一个简单的 POJO (Plain Old Java Object)
class User {
    private String name;
    private int age;
    // Getters and Setters (省略 for brevity)
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public int getAge() { return age; }
    public void setAge(int age) { this.age = age; }
}

测试

启动 Spring Boot 应用,你可以使用以下工具进行测试:

  • 浏览器:
    • 访问 http://localhost:8080/api/hello/World,会看到纯文本返回。
    • 访问 http://localhost:8080/api/user/Alice,浏览器会尝试显示 JSON。
  • PostmanInsomnia (强烈推荐): 这些是专业的 API 测试工具,可以发送不同类型的请求(GET, POST, PUT, DELETE)并查看格式化的 JSON 响应。
  • curl 命令:
    # 获取用户信息
    curl http://localhost:8080/api/user/Bob

响应会是这样的 JSON:

{
  "name": "Bob",
  "age": 30
}

总结与对比

特性 JAX-WS (SOAP) Spring Boot RESTful
协议 SOAP (基于 XML) HTTP (GET, POST, PUT, DELETE)
数据格式 XML (严格定义) JSON (轻量级,易读)
接口描述 WSDL (XML 文件) 通常无,或使用 OpenAPI/Swagger (JSON/YAML)
优点 - 标准化、跨语言、安全性高
- 自动生成客户端代码
- 简单、快速、轻量
- 无缝与现代 Web 前端集成
- 利用 Spring 生态
缺点 - 复杂、冗余
- 学习曲线陡峭
- 对移动端不友好
- 无官方标准,依赖约定
- 安全性需要自己实现
适用场景 - 企业级应用集成
- 金融、电信等对安全性和标准化要求高的领域
- 绝大多数现代 Web 应用
- 前后端分离项目
- 移动端后端服务
开发方式 定义接口 -> 实现类 -> 发布 定义 Controller -> 编写方法 -> 自动映射

最终建议

对于新项目,强烈推荐使用方式三:Spring Boot 开发 RESTful API,它更符合当前的技术趋势,开发效率更高,与前端和移动端的对接也更简单。

只有在有特殊需求(如必须与老旧的 SOAP 系统集成、或公司强制要求 SOAP 标准)时,才考虑使用 JAX-WS 或 Spring 整合的 JAX-WS。

分享:
扫描分享到社交APP
上一篇
下一篇