Developing a Web Service with CXF

Exclusive offer: get 50% off this eBook here
Apache CXF Web Service Development

Apache CXF Web Service Development — Save 50%

Develop and deploy SOAP and RESTful Web Services

$26.99    $13.50
by Naveen Balani | December 2009 | Open Source

In this article by Naveen Balani, we will have a look on programming web service with CXF which provides a robust programming model that offers simple and convenient APIs for web service development. We will basically illustrate a simple web service development using CXF and Spring-based configurations.

In this article we will basically study the sample Order Processing Application and discuss the following points:

  • Developing a service
  • Developing a client

The Order Processing Application

The objective of the Order Processing Application is to process a customer order. The order process functionality will generate the customer order, thereby making the order valid and approved. A typical scenario will be a customer making an order request to buy a particular item. The purchase department will receive the order request from the customer and prepare a formal purchase order. The purchase order will hold the details of the customer, the name of the item to be purchased, the quantity, and the price. Once the order is prepared, it will be sent to the Order Processing department for the necessary approval. If the order is valid and approved, then the department will generate the unique order ID and send it back to the Purchase department. The Purchase department will communicate the order ID back to the customer.

Apache CXF Web Service Development

For simplicity, we will look at the following use cases:

  • Prepare an order
  • Process the order

The client application will prepare an order and send it to the server application through a business method call. The server application will contain a web service that will process the order and generate a unique order ID. The generation of the unique order ID will signify order approval.

In real world applications a unique order ID is always accompanied by the date the order was approved. However, in this example we chose to keep it simple by only generating order ID.

Developing a service

Let's look specifically at how to create an Order Processing Web Service and then register it as a Spring bean using a JAX-WS frontend.

The Sun-based JAX-WS specification can be found at the following URL:

JAX-WS frontend offers two ways of developing a web service—Code-first and Contract-first. We will use the Code-first approach, that is, we will first create a Java class and convert this into a web service component. The first set of tasks will be to create server-side components.

In web service terminology, Code-first is termed as the Bottoms Up approach, and Contract-first is referred to as the Top Down approach.

To achieve this, we typically perform the following steps:

  • Create a Service Endpoint Interface (SEI) and define a business method to be used with the web service.
  • Create the implementation class and annotate it as a web service.
  • Create beans.xml and define the service class as a Spring bean using a JAX-WS frontend.

Creating a Service Endpoint Interface (SEI)

Let's first create the SEI for our Order Processing Application. We will name our SEI OrderProcess. The following code illustrates the OrderProcess SEI:

package demo.order;
import javax.jws.WebService;
public interface OrderProcess {
String processOrder(Order order);

As you can see from the preceding code, we created a Service Endpoint Interface named OrderProcess. The SEI is just like any other Java interface. It defines an abstract business method processOrder. The method takes an Order bean as a parameter and returns an order ID String value. The goal of the processOrder method is to process the order placed by the customer and return the unique order ID.

One significant thing to observe is the @WebService annotation. The annotation is placed right above the interface definition. It signifies that this interface is not an ordinary interface but a web service interface. This interface is known as Service Endpoint Interface and will have a business method exposed as a service method to be invoked by the client.

The @WebService annotation is part of the JAX-WS annotation library. JAX-WS provides a library of annotations to turn Plain Old Java classes into web services and specifies detailed mapping from a service defined in WSDL to the Java classes that will implement that service. The javax.jws.WebService annotation also comes with attributes that completely define a web service. For the moment we will ignore these attributes and proceed with our development.

The javax.jws.@WebMethod annotation is optional and is used for customizing the web service operation. The @WebMethod annotation provides the operation name and the action elements which are used to customize the name attribute of the operation and the SOAP action element in the WSDL document.

The following code shows the Order class:

package demo.order;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "Order")
public class Order {
private String customerID;
private String itemID;
private int qty;
private double price;
// Contructor
public Order() {
public String getCustomerID() {
return customerID;
public void setCustomerID(String customerID) {
this.customerID = customerID;
public String getItemID() {
return itemID;
public void setItemID(String itemID) {
this.itemID = itemID;
public int getQty() {
return qty;
public void setQty(int qty) {
this.qty = qty;
public double getPrice() {
return price;
public void setPrice(double price) {
this.price = price;

As you can see, we have added an @XmlRootElement annotation to the Order class. The @XmlRootElement is part of the Java Architecture for XML Binding (JAXB) annotation library. JAXB provides data binding capabilities by providing a convenient way to map XML schema to a representation in Java code. The JAXB shields the conversion of XML schema messages in SOAP messages to Java code without having the developers know about XML and SOAP parsing. CXF uses JAXB as the default data binding component.

The @XmlRootElement annotations associated with Order class map the Order class to the XML root element. The attributes contained within the Order object by default are mapped to @XmlElement. The @XmlElement annotations are used to define elements within the XML. The @XmlRootElement and @XmlElement annotations allow you to customize the namespace and name of the XML element. If no customizations are provided, then the JAXB runtime by default would use the same name of attribute for the XML element. CXF handles this mapping of Java objects to XML.

Developing a service implementation class

We will now develop the implementation class that will realize our OrderProcess SEI. We will name this implementation class OrderProcessImpl. The following code illustrates the service implementation class OrderProcessImpl:

public class OrderProcessImpl implements OrderProcess {
public String processOrder(Order order) {
String orderID = validate(order);
return orderID;
* Validates the order and returns the order ID
private String validate(Order order) {
String custID = order.getCustomerID();
String itemID = order.getItemID();
int qty = order.getQty();
double price = order.getPrice();
if (custID != null && itemID != null && !custID.equals("")
&& !itemID.equals("") && qty > 0
&& price > 0.0) {
return "ORD1234";
return null;

As we can see from the preceding code, our implementation class OrderProcessImpl is pretty straightforward. It also has @WebService annotation defined above the class declaration. The class OrderProcessImpl implements OrderProcess SEI. The class implements the processOrder method. The processOrder method checks for the validity of the order by invoking the validate method. The validate method checks whether the Order bean has all the relevant properties valid and not null.

It is recommended that developers explicitly implement OrderProcess SEI, though it may not be necessary. This can minimize coding errors by ensuring that the methods are implemented as defined.

Next we will look at how to publish the OrderProcess JAX-WS web service using Spring configuration.


Spring-based server bean

What makes CXF the obvious choice as a web service framework is its use of Spring-based configuration files to publish web service endpoints. It is the use of such configuration files that makes the development of web service convenient and easy with CXF.

Spring provides a lightweight container which works on the concept of Inversion of Control (IoC) or Dependency Injection (DI) architecture; it does so through the implementation of a configuration file that defines Java beans and its dependencies. By using Spring you can abstract and wire all the class dependencies in a single configuration file. The configuration file is often referred to as an Application Context or Bean Context file.

We will create a server side Spring-based configuration file and name it as beans.xml. The following code illustrates the beans.xml configuration file:

<beans xmlns=""
<import resource="classpath:META-INF/cxf/cxf.xml" />
<import resource="classpath:META-INF/cxf/cxf-extension- soap.xml" />
<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
address="/OrderProcess" />

Let's examine the previous code and understand what it really means. It first defines the necessary namespaces. It then defines a series of <import> statements. It imports cxf.xml, cxf-extension-soap.xml, and cxf-servlet.xml. These files are Springbased configuration files that define core components of CXF. They are used to kick start CXF runtime and load the necessary infrastructure objects such as WSDL manager, conduit manager, destination factory manager, and so on.

The <jaxws:endpoint> element in the beans.xml file specifies the OrderProcess web service as a JAX-WS  endpoint. The element is defined with the following three attributes:

  • id—specifies a unique identifier for a bean. In this case, jaxws:endpoint is a bean, and the id name is orderProcess.
  • implementor— specifies the actual web service implementation class. In this case, our implementor class is OrderProcessImpl.
  • address— specifies the URL address where the endpoint is to be published. The URL address must to be relative to the web context. For our example, the endpoint will be published using the relative path /OrderProcess.

The <jaxws:endpoint> element signifies that the CXF internally uses JAX-WS frontend to publish the web service. This element definition provides a short and convenient way to publish a web service. A developer need not have to write any Java class to publish a web service.

Apache CXF Web Service Development Develop and deploy SOAP and RESTful Web Services
Published: December 2009
eBook Price: $26.99
Book Price: $44.99
See more
Select your format and quantity:

Developing a client

In the previous section we discussed and illustrated how to develop and publish a web service. We now have the server-side code that publishes our OrderProcess web service. The next set of tasks will be to create the client-side code that will consume or invoke our OrderProcess web service. To achieve this, we will perform the following steps:

  • Develop the client-beans.xml to define the client factory class as a Spring bean using JAX-WS frontend
  • Develop a client Java application to invoke the web service

Developing a Spring-based client bean

We will create a client-side Spring-based configuration file and name it as client-beans.xml. The following code illustrates the client-beans.xml configuration file:

<beans xmlns=""
<jaxws:client id="orderClient" serviceClass=
"demo.order.OrderProcess" address=
"http://localhost:8080/orderapp/OrderProcess" />

The <jaxws:client> element in the client-beans.xml file specifies the client bean using JAX-WS frontend. The element is defined with the following three attributes:

  • id—specifies a unique identifier for a bean. In this case, jaxws:client is a bean and the id name is orderClient. The bean will represent an SEI.
  • serviceClass—specifies the web service SEI. In this case our SEI class is OrderProcess
  • address—specifies the URL address where the endpoint is published. In this case the endpoint is published at the URL address: http://localhost:8080/orderapp/OrderProcess

<jaxws:client> signifies the client bean that represents an OrderProcess SEI. The client application will make use of this SEI to invoke the web service. Again, CXF internally uses JAX-WS frontend to define this client-side component.

Developing web service client code

We will now create a standalone Java class to invoke our OrderProcess web service. The following code illustrates the client invocation of a web service method:

public final class Client {
public Client() {
public static void main(String args[]) throws Exception {
// START SNIPPET: client
ClassPathXmlApplicationContext context
= new ClassPathXmlApplicationContext(new String[]
OrderProcess client = (OrderProcess) context.
// Populate the Order bean
Order order = new Order();
String orderID = client.processOrder(order);
String message = (orderID == null) ?
"Order not approved" : "Order approved;
order ID is " + orderID;

As you can see from the above code, we have the main method that first loads the client-beans.xml configuration file. It uses the Spring application context component ClassPathXmlApplicationContext to load the configuration file. The context component's getBean method is passed the bean ID orderClient. This method will return the OrderProcess  SEIcomponent. Using the SEI, we then invoke the web service method processOrder. One thing to observe here is that the client always uses the interface to invoke a web service method. The processOrder method takes the Order bean as a parameter. The following code depicts the Order bean:

public class Order {
private String customerID;
private String itemID;
private int qty;
private double price;
// Contructor
public Order() {
// Getter and setter methods for the above declared properties

Before running the program, we will organize the code so far developed in the appropriate folder structure. You can create the folder structure, as shown in the following screenshot, and put the components in the respective sub folders

The above Order bean is populated with the valid values and passed to the processOrder method. The method will then process the order and return the unique order ID.

We have now finished developing server and client side components. To summarize, we created the OrderProcess service endpoint interface and the implementation class. We then created server and client-side Spring-based configuration files and finally we created the client application. The relevant components are developed and we are all set to run or execute our code. But before we do that, you will have to create one final component that will integrate Spring and CXF.

We need to wire Spring and CXF through web.xml. The following code illustrates the web.xml file:

<display-name>CXF Servlet</display-name>

Let's go through the above piece of code. The web.xml, as we know, is the web application configuration file that defines a servlet and its properties. The file defines CXFServlet, which acts as a front runner component that initiates the CXF environment. It defines the listener class ContextLoaderListener, which is responsible for loading the server-side configuration file beans.xml. So upon the web server startup, the order process web service endpoint will be registered and published.

Running the program

Apache CXF Web Service Development

The developed code will go into the following:

  • The Java code will go into the respective package folders
  • The beans.xml and web.xml will go into the webappWEB-INF folder
  • The client-beans.xml file will go into the demoorderclient folder

Once the code is organized, we will go about building and deploying it in the Tomcat server. It will typically involve three steps:

  • Building the code
  • Deploying the code
  • Executing the code

Building the code

Building the code means compiling the source Java code. We will use the ANT tool to do this. The ANT file is provided in Chapter2orderapp folder. The following code illustrates the sample build.xml build script:

<?xml version="1.0" encoding="UTF-8"?>
<project name="CXF Chapter2 example" default="build" basedir=".">
<import file="common_build.xml"/>
<target name="client" description=
"run demo client" depends="build">
<property name="param" value=""/>
<cxfrun classname="demo.order.client.Client" />
<target name="server" description=
"run demo server" depends="build">
<cxfrun classname="demo.spring.servlet.Server"/>
<property name="" value="orderapp"/>
<target name="war" depends="build">
<cxfwar filename="${}.war" webxml=
"webapp/WEB-INF/web.xml" />

Alongside build.xml, you will also find common_build.xml in the same folder. The common_buid.xml refers to CATALINA_HOME environment variable to find location of tomcat installation. Please make sure that you have set up the environment variables as mentioned in Appendix A. Open the command prompt window, go to C:orderapp folder and run the ant command. It will build the code and put the class files under the newly created build folder. The following figure shows the output generated upon running the ant command.

Apache CXF Web Service Development

Deploying the code

Having built the code, we will deploy it. Deployment effectively means building and moving the code archive to the server deploy path. We will be using the Tomcat web container to deploy and run the application. To deploy our built code, navigate to project root folder, and enter the following command:

ant deploy

This will build the WAR file and put it under the Tomcat server webapp path. For example, if you have installed the Tomcat under the root folder, then the WAR will be deployed to /Tomcat/webapp folder.

Executing the code

Following code deployment, we are all set to run the Order Process Application. You will execute the Java client program to invoke the Order Process web service. The program will invoke the processOrder method that will generate the order ID if the specified order is approved. Before running the client program, we need to start the Tomcat web server. There are several ways of starting the Tomcat server depending on the Tomcat version that is installed. Once the server is started, you need to run the client program by giving the following command at the command prompt window:

ant client

As you can see above, we are using Ant to run the client program. Upon executing this command, it will generate the following output:

Apache CXF Web Service Development

Thus we have successfully executed the order processing web service.


This article gives us an overview of a sample Order Processing Application and we saw how to develop a web service with Spring-based configuration. We also saw how to build, deploy, and execute a web service using ANT and Tomcat.

If you have read this article you may be interested to view :

Apache CXF Web Service Development Develop and deploy SOAP and RESTful Web Services
Published: December 2009
eBook Price: $26.99
Book Price: $44.99
See more
Select your format and quantity:

About the Author :

Naveen Balani

Naveen Balani works as a Software Architect with WebSphere Business Services Fabric (WBSF) Product out of IBM India Software Labs, Mumbai. He has over 9 years of industrial experience and has architected and implemented large scale BPM solutions. He started working with Web Services way back in 2001 and proposed the first MVC web services-based pattern ( in 2002. He is a Master Author with IBM developer works having published over 60 publications. He has co-authored books on Spring framework (published by Wrox) and Multiple IBM Redbooks on WebSphere Business Services Fabric and BPM 6.2 Product deployments.

Books From Packt


GlassFish Administration
GlassFish Administration

Blender 3D 2.49 Incredible Machines
Blender 3D 2.49 Incredible Machines

Tomcat 6 Developer's Guide
Tomcat 6 Developer's Guide

WordPress 2.8 Theme Design
WordPress 2.8 Theme Design

Apache Roller 4.0 – Beginner's Guide
Apache Roller 4.0 – Beginner's Guide

Beginning OpenVPN 2.0.9
Beginning OpenVPN 2.0.9

MooTools 1.2 Beginner's Guide
MooTools 1.2 Beginner's Guide

Funambol Mobile Open Source
Funambol Mobile Open Source


Your rating: None Average: 4 (1 vote)
Building CXF Webservice by
Excellent content to satrt with CXF Webservice development.

Post new comment

This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Enter the code without spaces and pay attention to upper/lower case.
Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software