Search This Blog

Saturday, 4 May 2013

Building Clients with the CXF API

In the previous posts we saw how to run a CXF application and test the web services using a JAX-WS client. While our previous client was built using classes from the JAX-WS API, there are other ways to execute the code too.
Consider the below client:
public static void main(String[] args) throws MalformedURLException {

 final String endpointAddress = "http://localhost:8080/WithSpring/services/echo";
 JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
 factory.setServiceClass(IEcho.class); //the service SEI
 IEcho client = (IEcho) factory.create();

 String reply = client.echoHi("Dude");
 System.out.println("Server said: " + reply);
The below shorter code will produce the same response. It uses a org.apache.cxf.jaxws.JaxWsProxyFactoryBean to create the client stub. This is a CXF class.
From the source code:
Factory for creating JAX-WS proxies, This class provides access to the internal 
properties used to set-up proxies. Using it provides more control  than the 
standard JAX-WS APIs.
If we are using Spring on the client, then the JaxWsProxyFactoryBean can be configured as a bean. In fact the stub can also be set up as a bean:
public static void main(String[] args) throws MalformedURLException {

 ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
 IEcho client = (IEcho) context.getBean("client");
The details are all in the spring configuration file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""

 <bean id="client" class=""
  factory-bean="clientFactory" factory-method="create" />

 <bean id="clientFactory" class="org.apache.cxf.jaxws.JaxWsProxyFactoryBean">
  <property name="serviceClass" value="" />
  <property name="address"
   value="http://localhost:8080/WithSpring/services/echo" />

We configured the JaxWsProxyFactoryBean  and then created a client bean specifying the factory instance method to be used to instantiate it.
This configuration can be further simplified:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
 xmlns:xsi="" xmlns:jaxws=""
 <jaxws:client id="client" serviceClass=""
  address="http://localhost:8080/WithSpring/services/echo" />
In this case we used the client element from the namespace. The element is a shortcut technique for the earlier style. It also creates a bean which we used in our main method.

1 comment: