杰瑞科技汇

Java Webservice用CXF如何快速开发?

Of course! Here is a comprehensive guide to creating a Java web service using Apache CXF, one of the most popular and powerful frameworks for the job.

Java Webservice用CXF如何快速开发?-图1
(图片来源网络,侵删)

This guide will cover:

  1. What is Apache CXF? - A quick overview.
  2. Core Concepts - JAX-WS and JAX-RS.
  3. Step-by-Step Example: Creating a JAX-WS Web Service
    • Setting up a Maven project.
    • Writing the service interface (SEI).
    • Writing the service implementation (SIB).
    • Publishing the service using a Spring configuration.
    • Testing the service with a client.
  4. JAX-RS (RESTful Services) Brief Overview
  5. Key Features and Advanced Topics

What is Apache CXF?

Apache CXF is an open-source, fully featured web services framework. It is a merger of two famous projects: Celtix (from the ObjectWeb consortium) and XFire. CXF provides a robust, standards-based way to build and develop web services.

Its main strengths are:

  • Standards Compliance: Implements key standards like JAX-WS (SOAP), JAX-RS (REST), WS-Security, WS-Policy, WS-Addressing, etc.
  • Flexibility: Supports multiple front-end programming models (JAX-WS, JAX-RS, JavaScript, etc.) and multiple data binding mechanisms ( JAXB, JSON, Aegis, etc.).
  • Transport Independence: Works over various protocols like SOAP/HTTP, REST/HTTP, JMS, etc.
  • Integration: Excellent integration with popular frameworks like Spring and OSGi.

Core Concepts: JAX-WS vs. JAX-RS

CXF is primarily a framework that implements two Java standard APIs for web services:

Java Webservice用CXF如何快速开发?-图2
(图片来源网络,侵删)

JAX-WS (Java API for XML Web Services)

  • Purpose: For building SOAP-based web services.
  • Protocol: Uses SOAP (Simple Object Access Protocol) messages, which are XML-based and often transported over HTTP.
  • Characteristics:
    • Platform and language independent.
    • Highly extensible with WS-* standards (Security, Transactions, etc.).
    • More complex due to the SOAP envelope and WS-* specifications.
    • Good for enterprise-level applications requiring high security and reliability.
  • CXF's Role: CXF is a JAX-WS implementation provider. You write your code using the JAX-WS annotations (@WebService, @WebMethod, etc.), and CXF provides the runtime to convert your Java objects to/from SOAP messages.

JAX-RS (Java API for RESTful Web Services)

  • Purpose: For building RESTful web services.
  • Protocol: Uses standard HTTP methods (GET, POST, PUT, DELETE) to perform CRUD operations on resources.
  • Characteristics:
    • Lightweight and simple.
    • Uses standard HTTP, making it easy to consume from any client (browser, mobile app, etc.).
    • Data is typically exchanged in JSON or XML format.
    • Stateless and cache-friendly.
  • CXF's Role: CXF is a JAX-RS implementation provider. You write your code using JAX-RS annotations (@Path, @GET, @POST, @Produces, @Consumes), and CXF handles the routing and HTTP request/response handling.

Step-by-Step Example: JAX-WS Web Service

Let's create a simple "Hello World" web service using JAX-WS and Spring. This is a very common and powerful setup.

Prerequisites

  • Java Development Kit (JDK) 8 or later.
  • Apache Maven.
  • Your favorite IDE (IntelliJ, Eclipse, VS Code).

Step 1: Create a Maven Project

Create a new Maven project and add the following dependencies to your pom.xml. We'll use the cxf-spring-boot-starter-jaxws for a simpler setup, but we'll also show the traditional Spring XML configuration.

<dependencies>
    <!-- CXF JAX-WS Starter for Spring Boot -->
    <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-spring-boot-starter-jaxws</artifactId>
        <version>3.5.5</version> <!-- Use the latest version -->
    </dependency>
    <!-- For JAX-WS annotations and API -->
    <dependency>
        <groupId>jakarta.jakartaee-api</groupId>
        <artifactId>jakarta.jakartaee-api</artifactId>
        <version>9.1.0</version>
        <scope>provided</scope>
    </dependency>
    <!-- Spring Boot Starter for running the application -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

Step 2: Create the Service Interface (SEI - Service Endpoint Interface)

This interface defines the contract of your web service. The @WebService annotation marks it as a web service.

// src/main/java/com/example/demo/HelloWorld.java
package com.example.demo;
import jakarta.jws.WebMethod;
import jakarta.jws.WebParam;
import jakarta.jws.WebService;
@WebService(name = "HelloWorld", targetNamespace = "http://demo.example.com/")
public interface HelloWorld {
    @WebMethod
    String sayHello(@WebParam(name = "name") String name);
    @WebMethod
    String getServerTime();
}

Step 3: Create the Service Implementation (SIB - Service Implementation Bean)

This class implements the interface and contains the actual business logic.

Java Webservice用CXF如何快速开发?-图3
(图片来源网络,侵删)
// src/main/java/com/example/demo/HelloWorldImpl.java
package com.example.demo;
import org.springframework.stereotype.Component;
import jakarta.jws.WebService;
@WebService(serviceName = "HelloWorldService", endpointInterface = "com.example.demo.HelloWorld")
@Component // Important: Make it a Spring bean
public class HelloWorldImpl implements HelloWorld {
    @Override
    public String sayHello(String name) {
        return "Hello, " + name + "!";
    }
    @Override
    public String getServerTime() {
        return "Server time is: " + new java.util.Date();
    }
}

Note: The @WebService annotation on the implementation class is crucial. It tells CXF which interface this class implements for the web service.

Step 4: Configure and Publish the Service (Spring Boot Way)

With Spring Boot, this is incredibly simple. CXF auto-configuration does most of the work. You just need to expose the service via a @Bean.

// src/main/java/com/example/demo/CxfConfig.java
package com.example.demo;
import org.apache.cxf.Bus;
import org.apache.cxf.jaxws.EndpointImpl;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import jakarta.xml.ws.Endpoint;
@Configuration
public class CxfConfig {
    @Bean
    public Endpoint helloWorldEndpoint(Bus bus) {
        EndpointImpl endpoint = new EndpointImpl(bus, new HelloWorldImpl());
        // The URL where the service will be available
        endpoint.publish("/helloWorld");
        return endpoint;
    }
}

Step 5: Run the Application

Create a main Spring Boot application class.

// src/main/java/com/example/demo/DemoApplication.java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

Now, run the DemoApplication main method. Once started, your web service is published!

  • WSDL (Web Services Description Language) URL: http://localhost:8080/helloWorld?wsdl

    This is the most important URL. It describes your service, its operations, and how to interact with it. Clients will use this URL to generate their client-side code.

Step 6: Create a Client to Test the Service

CXF provides a handy wsdl2java tool to generate a client from the WSDL. But for a quick test, you can use the following Java client.

First, add this dependency to your pom.xml for client-side CXF tools:

<dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-rt-frontend-jaxws</artifactId>
    <version>3.5.5</version>
</dependency>

Now, create a client class:

// src/test/java/com/example/demo/HelloWorldClient.java
package com.example.demo;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
public class HelloWorldClient {
    public static void main(String[] args) {
        // 1. Create a JaxWsProxyFactoryBean
        JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
        // 2. Set the service class
        factory.setServiceClass(HelloWorld.class);
        // 3. Set the WSDL URL or the service endpoint address
        factory.setAddress("
分享:
扫描分享到社交APP
上一篇
下一篇