Apache CXF with JAX-WS
JAX-WS is the standard Java API for SOAP web services. CXF implements it and adds tooling, transports, and Spring integration. Compared with a bare POJO endpoint, JAX-WS makes the contract explicit through a service endpoint interface (SEI).
Interface and implementation
package com.example.ws;
import jakarta.jws.WebMethod;
import jakarta.jws.WebParam;
import jakarta.jws.WebService;
@WebService(targetNamespace = "http://ws.example.com/")
public interface Calculator {
@WebMethod(operationName = "add")
int add(@WebParam(name = "a") int a,
@WebParam(name = "b") int b);
}
package com.example.ws;
import jakarta.jws.WebService;
@WebService(
endpointInterface = "com.example.ws.Calculator",
targetNamespace = "http://ws.example.com/",
serviceName = "CalculatorService",
portName = "CalculatorPort"
)
public class CalculatorImpl implements Calculator {
@Override
public int add(int a, int b) {
return a + b;
}
}
The endpointInterface attribute links the implementation to the SEI. CXF reads the annotations from the interface, so keep both definitions synchronized.
SOAP style
JAX-WS defaults to document/literal wrapped messages. Each operation has a wrapper element named after the method, which is the most interoperable style. The @SOAPBinding annotation can change the style or use of the binding, but most services should keep the default.
import jakarta.jws.soap.SOAPBinding;
import jakarta.jws.soap.SOAPBinding.Style;
@SOAPBinding(style = Style.DOCUMENT, use = SOAPBinding.Use.LITERAL)
@WebService
public interface Reporting {
String report(int year);
}
Faults
A checked exception annotated with @WebFault becomes a SOAP fault with a structured detail element. Unchecked exceptions become generic faults. Clients see faults as exceptions, so document the ones that are part of the contract.
@WebFault(name = "InvalidYear")
public class InvalidYearException extends Exception {
public InvalidYearException(String message) {
super(message);
}
}
Handlers and interceptors
JAX-WS handlers operate on the SOAP message at the protocol level and are portable across implementations. CXF interceptors are more powerful but specific to CXF. Use handlers for standards-based header processing and interceptors for CXF-specific logging or transformation.
Code-first or contract-first
This chapter is code-first: Java is the source and the WSDL is generated. The WSDL-first chapters reverse the flow. Both are valid; choose based on who owns the contract and how many clients depend on it.
JAX-WS versus POJO endpoints
- The SEI documents operations and types before the server runs.
- Clients can be generated from the WSDL with standard tools.
- Overloaded and annotated operations are easier to control.
- The extra interface is worthwhile once more than one team consumes the service.
Back to course overview · Previous: Create Client & Test · Next: Create JAX WS Server