Apache CXF with JAX-WS Example

‮th‬tps://www.theitroad.com

here's an example of how to use Apache CXF with JAX-WS to create a simple web service.

  1. First, we need to create a JAX-WS annotated class that will serve as our web service implementation. Let's create a class called "HelloServiceImpl" that will have a single method called "sayHello" that takes a String parameter and returns a String.
import javax.jws.WebService;

@WebService(endpointInterface = "com.example.HelloService")
public class HelloServiceImpl implements HelloService {

    public String sayHello(String name) {
        return "Hello " + name;
    }
}
  1. Next, we need to create a CXF configuration file called "cxf.xml" that will define our web service. Here's what the file should look like:
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:jaxws="http://cxf.apache.org/jaxws"
    xmlns:cxf="http://cxf.apache.org/core"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    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
        http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd">

    <import resource="classpath:META-INF/cxf/cxf.xml" />

    <jaxws:endpoint id="helloService"
        implementor="com.example.HelloServiceImpl"
        address="/hello">
    </jaxws:endpoint>

</beans>

In this file, we're defining a JAX-WS endpoint with an ID of "helloService" that will use our "HelloServiceImpl" implementation and be accessible at the "/hello" URL.

  1. Finally, we need to create a main method that will start up our web service. Here's what the main method should look like:
public static void main(String[] args) {
    // Create the Spring context
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:cxf.xml");

    // Wait for the user to terminate the program
    System.out.println("Press Enter to exit.");
    System.in.read();

    // Close the Spring context
    context.close();
}

In this method, we're creating a Spring context from our "cxf.xml" file and waiting for the user to terminate the program.

That's it! With these three steps, we've created a simple web service using Apache CXF and JAX-WS. To test the service, you can open a web browser or a tool like SOAPUI and navigate to the URL "http://localhost:8080/hello?wsdl". You should see a WSDL document that describes the "sayHello" method of our "HelloServiceImpl" implementation.