Apache CXF with JAX-RS Example

htt‮p‬s://www.theitroad.com

here's an example of how to use Apache CXF to create a RESTful web service using JAX-RS.

  1. First, we need to add the CXF dependencies to our project. We can do this by adding the following dependencies to our Maven pom.xml file:
<dependencies>
    <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-rt-frontend-jaxrs</artifactId>
        <version>3.4.5</version>
    </dependency>
    <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-rt-transports-http</artifactId>
        <version>3.4.5</version>
    </dependency>
</dependencies>
  1. Next, we can create a resource class that will define our RESTful web service. Let's create a class called "HelloResource" that will have a single method called "sayHello" that takes a String parameter and returns a String:
package com.example;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;

@Path("/hello")
public class HelloResource {

    @GET
    @Path("/{name}")
    @Produces("text/plain")
    public String sayHello(@PathParam("name") String name) {
        return "Hello " + name;
    }

}

In this class, we're using JAX-RS annotations to specify that the "sayHello" method should be called when a GET request is made to the "/hello/{name}" 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:
import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;

public class HelloServicePublisher {

    public static void main(String[] args) {
        // Create the JAX-RS server
        JAXRSServerFactoryBean factory = new JAXRSServerFactoryBean();
        factory.setAddress("http://localhost:8080/");
        factory.setServiceBean(new HelloResource());

        // Start the server
        factory.create();

        // Wait for the user to terminate the program