Работа с Apache CXF в экосистеме Java

Раздел: Библиотеки Java -> Библиотеки Apache

Apache CXF в Java: практическое применение

Apache CXF представляет набор библиотек для построения и потребления веб-сервисов на Java. Ключевые направления: JAX-WS для SOAP и JAX-RS для REST. Наиболее часто применяемый подход: контрактный SOAP-сервис с WSDL и Java-реализацией интерфейса. Такой вариант дает строгую типизацию, совместимость с корпоративными системами и генерацию кода.

Зависимости Maven для JAX-WS.

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

Java apache cxf (apache cxf в java)

Версия 4.0.5 рассчитана на Java 17. Для более старых JDK подходит ветка 3.5.x.

Интерфейс сервиса.

package ru.example.cxf;

import jakarta.jws.WebMethod;
import jakarta.jws.WebService;

@WebService
public interface CalculatorService {
    @WebMethod
    int add(int a, int b);
}

Аннотация @WebService открывает методы для SOAP. Пакет jakarta.jws используется в CXF 4.x. В CXF 3.x применяется javax.jws.

Реализация сервиса.

package ru.example.cxf;

import jakarta.jws.WebService;

@WebService(endpointInterface = "ru.example.cxf.CalculatorService")
public class CalculatorServiceImpl implements CalculatorService {
    @Override
    public int add(int a, int b) {
        return a + b;
    }
}

Публикация endpoint.

package ru.example.cxf;

import jakarta.xml.ws.Endpoint;

public class ServerLauncher {
    public static void main(String[] args) {
        Endpoint.publish("http://localhost:8080/calculator", new CalculatorServiceImpl());
        System.out.println("SOAP service started");
    }
}

Запуск main публикует SOAP-сервис по адресу http://localhost:8080/calculator?wsdl.

Клиент через JaxWsProxyFactoryBean.

package ru.example.cxf;

import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;

public class ClientLauncher {
    public static void main(String[] args) {
        JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
        factory.setServiceClass(CalculatorService.class);
        factory.setAddress("http://localhost:8080/calculator");
        CalculatorService client = (CalculatorService) factory.create();
        int result = client.add(2, 3);
        System.out.println("Result: " + result);
    }
}
Result: 5
Типичная ошибка: несовпадение namespace или endpointInterface. Клиент получает javax.xml.ws.WebServiceException. Решение: проверка атрибута targetNamespace в WSDL и значения endpointInterface в реализации. Второй частый случай: отсутствие зависимости cxf-rt-transports-http-jetty для standalone запуска. Без нее Endpoint.publish не находит HTTP-транспорт.

Как создать REST-сервис на Apache CXF вместо SOAP?

Для REST применяется модуль JAX-RS. Он подходит для легких HTTP API, JSON и простых URL. Зависимости: cxf-rt-frontend-jaxrs, cxf-rt-rs-extension-providers, jackson-jaxrs-json-provider.

<dependency>
  <groupId>org.apache.cxf</groupId>
  <artifactId>cxf-rt-frontend-jaxrs</artifactId>
  <version>4.0.5</version>
</dependency>
<dependency>
  <groupId>org.apache.cxf</groupId>
  <artifactId>cxf-rt-rs-extension-providers</artifactId>
  <version>4.0.5</version>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.jaxrs</groupId>
  <artifactId>jackson-jaxrs-json-provider</artifactId>
  <version>2.15.2</version>
</dependency>
package ru.example.cxf.rest;

import jakarta.ws.rs.*;
import jakarta.ws.rs.core.MediaType;
import java.util.List;

@Path("/users")
public class UserResource {
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public List<User> list() {
        return List.of(new User(1, "Anna"), new User(2, "Boris"));
    }

    public static class User {
        public int id;
        public String name;
        public User(int id, String name) {
            this.id = id;
            this.name = name;
        }
    }
}
package ru.example.cxf.rest;

import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
import org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider;
import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;

public class RestServer {
    public static void main(String[] args) {
        JAXRSServerFactoryBean factory = new JAXRSServerFactoryBean();
        factory.setResourceClasses(UserResource.class);
        factory.setResourceProvider(UserResource.class, new SingletonResourceProvider(new UserResource()));
        factory.setProvider(new JacksonJsonProvider());
        factory.setAddress("http://localhost:8081/rest");
        factory.create().start();
        System.out.println("REST service started");
    }
}
Ошибка: HTTP 415 Unsupported Media Type при POST без Content-Type. Решение: указать @Consumes(MediaType.APPLICATION_JSON) и заголовок Content-Type: application/json. Еще одна проблема: отсутствие провайдера Jackson, из-за чего CXF возвращает XML или ошибку. Решение: регистрация JacksonJsonProvider.

Как подключить Apache CXF к Spring Boot для SOAP-сервиса?

Spring Boot starter упрощает конфигурацию endpoint, WSDL и внедрение зависимостей. Зависимость: cxf-spring-boot-starter-jaxws.

<dependency>
  <groupId>org.apache.cxf</groupId>
  <artifactId>cxf-spring-boot-starter-jaxws</artifactId>
  <version>4.0.5</version>
</dependency>
package ru.example.cxf.boot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class CxfBootApplication {
    public static void main(String[] args) {
        SpringApplication.run(CxfBootApplication.class, args);
    }
}
package ru.example.cxf.boot;

import jakarta.jws.WebService;
import org.springframework.stereotype.Service;

@Service
@WebService(serviceName = "GreetingService")
public class GreetingService {
    public String greet(String name) {
        return "Hello, " + name;
    }
}
package ru.example.cxf.boot;

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 greetingEndpoint(Bus bus, GreetingService service) {
        EndpointImpl endpoint = new EndpointImpl(bus, service);
        endpoint.publish("/greeting");
        return endpoint;
    }
}

Свойства application.properties: cxf.path=/services. После запуска WSDL доступен по адресу http://localhost:8080/services/greeting?wsdl.

Проблема: конфликт версий Jakarta и javax. В Spring Boot 3 применяются jakarta.jws и CXF 4.x. В Spring Boot 2 нужны javax.jws и CXF 3.5.x. Смешивание пакетов приводит к ClassNotFoundException.

Как добавить WS-Security UsernameToken в Apache CXF?

WS-Security применяется для аутентификации SOAP-сообщений. В CXF используются WSS4JInInterceptor и WSS4JOutInterceptor. Зависимость: cxf-rt-ws-security.

<dependency>
  <groupId>org.apache.cxf</groupId>
  <artifactId>cxf-rt-ws-security</artifactId>
  <version>4.0.5</version>
</dependency>
import java.util.HashMap;
import java.util.Map;
import org.apache.cxf.ws.security.wss4j.WSS4JOutInterceptor;
import org.apache.wss4j.dom.WSConstants;
import org.apache.wss4j.dom.handler.WSHandlerConstants;

public class SecurityClient {
    public static void main(String[] args) {
        JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
        factory.setServiceClass(CalculatorService.class);
        factory.setAddress("http://localhost:8080/secure-calculator");

        Map<String, Object> outProps = new HashMap<>();
        outProps.put(WSHandlerConstants.ACTION, WSHandlerConstants.USERNAME_TOKEN);
        outProps.put(WSHandlerConstants.USER, "admin");
        outProps.put(WSHandlerConstants.PASSWORD_TYPE, WSConstants.PW_TEXT);
        outProps.put(WSHandlerConstants.PW_CALLBACK_CLASS, PasswordCallbackHandler.class.getName());
        factory.getOutInterceptors().add(new WSS4JOutInterceptor(outProps));

        CalculatorService client = (CalculatorService) factory.create();
        System.out.println(client.add(10, 20));
    }
}
Ошибка: MustUnderstand headers не обработаны. Решение: на сервере добавление WSS4JInInterceptor с теми же действиями. Проблема: пароль в открытом виде. Для тестов PW_TEXT допустим, для production лучше PW_DIGEST или сертификаты.

Как вызвать SOAP-сервис без генерации стабов?

Динамический клиент применяется, когда WSDL доступен во время выполнения. Класс JaxWsDynamicClientFactory создает client по WSDL.

import org.apache.cxf.jaxws.JaxWsDynamicClientFactory;

public class DynamicClient {
    public static void main(String[] args) throws Exception {
        JaxWsDynamicClientFactory factory = JaxWsDynamicClientFactory.newInstance();
        org.apache.cxf.endpoint.Client client = factory.createClient(
            "http://localhost:8080/calculator?wsdl"
        );
        Object[] result = client.invoke("add", 4, 6);
        System.out.println("Result: " + result[0]);
    }
}
Result: 10
Проблема: медленный первый вызов из-за загрузки WSDL и компиляции. Решение: кеширование client или переход на статический stub. Ошибка: неверное имя операции. Решение: проверка значения в WSDL operation name.

Расширенные примеры Apache CXF

Контрактный SOAP-сервис с Maven-плагином cxf-codegen-plugin

Подход contract-first начинается с WSDL. Плагин генерирует Java-интерфейсы во время сборки. Это снижает риск расхождений между контрактом и кодом.

Пример
<plugin>
  <groupId>org.apache.cxf</groupId>
  <artifactId>cxf-codegen-plugin</artifactId>
  <version>4.0.5</version>
  <executions>
    <execution>
      <id>generate-sources</id>
      <phase>generate-sources</phase>
      <goals><goal>wsdl2java</goal></goals>
      <configuration>
        <wsdlOptions>
          <wsdlOption>
            <wsdl>src/main/resources/calculator.wsdl</wsdl>
          </wsdlOption>
        </wsdlOptions>
      </configuration>
    </execution>
  </executions>
</plugin>

После mvn generate-sources в target/generated-sources/cxf появляется интерфейс. Реализация использует его как endpointInterface.

Пример
@WebService(endpointInterface = "ru.example.calculator.CalculatorPortType")
public class CalculatorPortImpl implements CalculatorPortType {
    @Override
    public int add(int a, int b) {
        return a + b;
    }
}

WSDL можно получить через EndpointImpl или через standalone Endpoint.publish.

Spring Boot SOAP endpoint с WSDL и SOAP UI

Конфигурация для Spring Boot 3 и CXF 4.

Пример
@Configuration
public class SoapConfig {
    @Bean
    public Endpoint calculatorEndpoint(Bus bus, CalculatorService service) {
        EndpointImpl endpoint = new EndpointImpl(bus, service);
        endpoint.publish("/calculator");
        return endpoint;
    }
}
Пример
@Service
@WebService(serviceName = "CalculatorService", targetNamespace = "http://example.ru/calc")
public class CalculatorService {
    public int add(int a, int b) {
        return a + b;
    }
}

Запрос SOAP через curl:

Пример
curl -X POST http://localhost:8080/services/calculator -H "Content-Type: text/xml; charset=UTF-8" -d '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:cal="http://example.ru/calc">
        <soapenv:Header/>
        <soapenv:Body>
          <cal:add><arg0>3</arg0><arg1>7</arg1></cal:add>
        </soapenv:Body>
      </soapenv:Envelope>'

Ответ содержит значение 10 в элементе return.

<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <ns2:addResponse xmlns:ns2="http://example.ru/calc">
      <return>10</return>
    </ns2:addResponse>
  </soap:Body>
</soap:Envelope>

REST-сервис CXF с JSON, POST и валидацией

Пример JAX-RS ресурса с созданием пользователя.

Пример
@Path("/users")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class UserResource {
    private final Map<Integer, User> storage = new ConcurrentHashMap<>();

    @POST
    public Response create(User user) {
        if (user.id <= 0) {
            return Response.status(400).entity("Invalid id").build();
        }
        storage.put(user.id, user);
        return Response.status(201).entity(user).build();
    }

    @GET
    @Path("/{id}")
    public Response get(@PathParam("id") int id) {
        User user = storage.get(id);
        if (user == null) {
            return Response.status(404).build();
        }
        return Response.ok(user).build();
    }
}
Пример
JAXRSServerFactoryBean factory = new JAXRSServerFactoryBean();
factory.setResourceClasses(UserResource.class);
factory.setResourceProvider(UserResource.class, new SingletonResourceProvider(new UserResource()));
factory.setProvider(new JacksonJsonProvider());
factory.setAddress("http://localhost:8081/api");
factory.create().start();
Пример
curl -X POST http://localhost:8081/api/users -H "Content-Type: application/json" -d '{"id":1,"name":"Anna"}'
{"id":1,"name":"Anna"}

Логирование SOAP-сообщений через interceptors

Перехватчики CXF дают доступ к входящим и исходящим SOAP-сообщениям. Это помогает при отладке.

Пример
import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;

public class LoggingClient {
    public static void main(String[] args) {
        JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
        factory.setServiceClass(CalculatorService.class);
        factory.setAddress("http://localhost:8080/calculator");
        factory.getInInterceptors().add(new LoggingInInterceptor());
        factory.getOutInterceptors().add(new LoggingOutInterceptor());
        CalculatorService client = (CalculatorService) factory.create();
        System.out.println(client.add(5, 8));
    }
}
INFO: Inbound Message
----------------------------
ID: 1
Address: http://localhost:8080/calculator
Encoding: UTF-8
Content-Type: text/xml; charset=UTF-8
Payload: <soap:Envelope>...</soap:Envelope>
----------------------------
13

Асинхронный вызов SOAP-сервиса

Асинхронный режим полезен для долгих операций. JAX-WS поддерживает AsyncHandler и Response.

Пример
import jakarta.xml.ws.AsyncHandler;
import jakarta.xml.ws.Response;

public class AsyncClient {
    public static void main(String[] args) throws Exception {
        JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
        factory.setServiceClass(CalculatorService.class);
        factory.setAddress("http://localhost:8080/calculator");
        CalculatorService client = (CalculatorService) factory.create();

        Response<Integer> response = client.addAsync(11, 12, new AsyncHandler<Integer>() {
            @Override
            public void handleResponse(Response<Integer> res) {
                try {
                    System.out.println("Async result: " + res.get());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        System.out.println("Request sent");
        Thread.sleep(2000);
    }
}
Request sent
Async result: 23

MTOM для передачи бинарных данных

MTOM позволяет передавать большие вложения без base64-разрядности. В CXF аннотация @MTOM включает оптимизацию.

Пример
import jakarta.activation.DataHandler;
import jakarta.jws.WebService;
import jakarta.xml.ws.soap.MTOM;

@MTOM
@WebService
public class FileService {
    public String upload(DataHandler handler) {
        return "Received bytes: " + handler.getDataSource().getName();
    }
}
Пример
import jakarta.activation.DataHandler;
import jakarta.activation.FileDataSource;

public class MtomClient {
    public static void main(String[] args) {
        JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
        factory.setServiceClass(FileService.class);
        factory.setAddress("http://localhost:8080/files");
        FileService client = (FileService) factory.create();
        DataHandler handler = new DataHandler(new FileDataSource("/tmp/report.pdf"));
        System.out.println(client.upload(handler));
    }
}
Received bytes: report.pdf

Обработка ошибок SOAP с @WebFault

Исключения можно превращать в SOAP Fault. Клиент получает структурированную ошибку.

Пример
import jakarta.jws.WebService;
import jakarta.xml.ws.WebFault;

@WebFault(name = "ValidationFault")
public class ValidationException extends Exception {
    private final String details;

    public ValidationException(String message, String details) {
        super(message);
        this.details = details;
    }

    public String getFaultInfo() {
        return details;
    }
}
Пример
@WebService
public class OrderService {
    public String createOrder(int amount) throws ValidationException {
        if (amount <= 0) {
            throw new ValidationException("Invalid amount", "amount=" + amount);
        }
        return "Order created";
    }
}
Пример
try {
    orderService.createOrder(-5);
} catch (ValidationException e) {
    System.out.println("Fault: " + e.getMessage());
    System.out.println("Details: " + e.getFaultInfo());
}
Fault: Invalid amount
Details: amount=-5

Тестирование CXF-сервиса через JUnit 5

Для интеграционного теста можно поднять endpoint на случайном порту и вызвать клиент.

Пример
import org.junit.jupiter.api.*;
import static org.junit.jupiter.api.Assertions.*;

class CalculatorServiceTest {
    private static Endpoint endpoint;

    @BeforeAll
    static void start() {
        endpoint = Endpoint.publish("http://localhost:9090/calc", new CalculatorServiceImpl());
    }

    @AfterAll
    static void stop() {
        endpoint.stop();
    }

    @Test
    void addReturnsSum() {
        JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
        factory.setServiceClass(CalculatorService.class);
        factory.setAddress("http://localhost:9090/calc");
        CalculatorService client = (CalculatorService) factory.create();
        assertEquals(9, client.add(4, 5));
    }
}
Test passed: addReturnsSum

Apache CXF в Java - comments

En
Java apache cxf (java)