Apache CXF with POJO Example

https://‮figi.www‬tidea.com

Here's an example of how to use Apache CXF with POJOs (Plain Old Java Objects) to create a simple web service.

  1. First, we need to create a POJO class that will serve as our web service implementation. Let's create a class called "HelloService" that will have a single method called "sayHello" that takes a String parameter and returns a String.
public class 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.HelloService"
        address="/hello">
    </jaxws:endpoint>

</beans>

In this file, we're defining a JAX-WS endpoint with an ID of "helloService" that will use our "HelloService" 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");

    // Get the HelloService bean from the context
    HelloService helloService = context.getBean("helloService", HelloService.class);

    // 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, getting the "HelloService" bean from the context, and then 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 POJOs. 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 "HelloService" implementation.