Hướng dẫn tích hợp Apache CXF với Spring MVC và MyBatis để triển khai WebService

Việc kết hợp Apache CXF vào hệ sinh thái Spring MVC và MyBatis cho phép các nhà phát triển xây dựng hệ thống WebService chuẩn SOAP một cách nhanh chóng. Dưới đây là quy trình chi tiết để triển khai cả phía Server (máy chủ) và Client (máy khách) sử dụng cấu hình XML và Maven.

1. Cấu hình các thành phần phía Server

Trước tiên, chúng ta cần định nghĩa một đối tượng dữ liệu (POJO) để trao đổi thông tin qua WebService.


package com.tech.model;

import java.io.Serializable;
import java.util.Date;

public class DeviceRecord implements Serializable {
    private Integer recordId;
    private Integer sensorId;
    private String dataValue;
    private Date timestamp;

    // Getters and Setters
    public Integer getRecordId() { return recordId; }
    public void setRecordId(Integer recordId) { this.recordId = recordId; }
    
    public Integer getSensorId() { return sensorId; }
    public void setSensorId(Integer sensorId) { this.sensorId = sensorId; }
    
    public String getDataValue() { return dataValue; }
    public void setDataValue(String dataValue) { this.dataValue = dataValue; }
    
    public Date getTimestamp() { return timestamp; }
    public void setTimestamp(Date timestamp) { this.timestamp = timestamp; }
}

Tiếp theo, định nghĩa Interface cho dịch vụ và lớp triển khai (Implementation). Lưu ý việc sử dụng Annotation @WebServicetargetNamespace để định danh dịch vụ.


package com.tech.service;

import javax.jws.WebService;
import com.tech.model.DeviceRecord;

@WebService(targetNamespace = "http://api.tech.example.com/")
public interface DataService {
    DeviceRecord fetchRecordById(Integer id);
}

Lớp triển khai dịch vụ sẽ gọi đến tầng nghiệp vụ hoặc DAO (MyBatis) để truy vấn cơ sở dữ liệu MySQL.


package com.tech.service.impl;

import javax.jws.WebService;
import org.springframework.beans.factory.annotation.Autowired;
import com.tech.model.DeviceRecord;
import com.tech.service.DataService;
import com.tech.dao.DeviceMapper;

@WebService(
    endpointInterface = "com.tech.service.DataService",
    serviceName = "DeviceDataWebService"
)
public class DataServiceImpl implements DataService {

    @Autowired
    private DeviceMapper deviceMapper;

    @Override
    public DeviceRecord fetchRecordById(Integer id) {
        return deviceMapper.findDeviceById(id);
    }
}

2. Cấu hình Spring và Web XML

Trong file applicationContext.xml, cần khai báo namespace của CXF và đăng ký endpoint cho dịch vụ.


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:jaxws="http://cxf.apache.org/jaxws"
       xsi:schemaLocation="
           http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
           http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">

    <!-- Đăng ký WebService Endpoint -->
    <jaxws:endpoint 
        id="deviceDataApi" 
        implementor="com.tech.service.impl.DataServiceImpl" 
        address="/DeviceService" />

</beans>

Cấu hình web.xml để điều hướng các yêu cầu WebService thông qua CXFServlet.


<servlet>
    <servlet-name>CXFServlet</servlet-name>
    <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>CXFServlet</servlet-name>
    <url-pattern>/ws/*</url-pattern>
</servlet-mapping>

Sau khi khởi chạy ứng dụng, bạn có thể kiểm tra danh sách dịch vụ tại địa chỉ: http://localhost:8080/ws/. File WSDL sẽ có dạng: http://localhost:8080/ws/DeviceService?wsdl.

3. Triển khai phía Client để gọi dịch vụ

Tại phía Client, chúng ta cần bản sao của Interface DataService và POJO tương ứng. Sử dụng JaxWsProxyFactoryBean để tạo proxy gọi đến Server.


package com.tech.client;

import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import com.tech.service.DataService;
import com.tech.model.DeviceRecord;

public class WebServiceClient {
    public static void main(String[] args) {
        // Khởi tạo Factory
        JaxWsProxyFactoryBean proxyFactory = new JaxWsProxyFactoryBean();
        
        // Thiết lập lớp dịch vụ và địa chỉ Endpoint
        proxyFactory.setServiceClass(DataService.class);
        proxyFactory.setAddress("http://localhost:8080/ws/DeviceService");
        
        // Tạo đối tượng thực thi
        DataService service = (DataService) proxyFactory.create();
        
        // Thực hiện gọi hàm từ xa
        DeviceRecord result = service.fetchRecordById(101);
        if (result != null) {
            System.out.println("Giá trị nhận được: " + result.getDataValue());
        }
    }
}

4. Lưu ý về quản lý Dependency (Maven)

Khi sử dụng Maven, cần chú ý loại bỏ các thư viện cũ hoặc bị xung đột như asm hoặc XmlSchema nếu sử dụng CXF phiên bản 3.x trở lên. Các dependency cơ bản bao gồm:

  • cxf-rt-frontend-jaxws
  • cxf-rt-transports-http
  • wsdl4j

Từ phiên bản Apache CXF 3.x, các file cấu hình như cxf.xml thường không còn bắt buộc phải import thủ công trong Spring XML như các phiên bản cũ, giúp cấu hình trở nên gọn nhẹ hơn.

Thẻ: spring-mvc mybatis apache-cxf soap-webservice java-ee

Đăng vào ngày 31 tháng 8 lúc 15:22