Thursday, May 21, 2009

Apache cxf using annotations and integration with Spring

Today I will show you how you can create a webservice using Apache CXF version 2.2.1. I will be building this webservice on top of my previous application.

Create a interface AirlineManager to expose methods over webservice. The create method takes airline code and name to create a Airline record in database. Annotation @WebService tells that this is a interface for webservice.


import javax.jws.WebService;

public interface AirlineManager {
public void create(String code, String name);

Implement the above webservice interface. We are using AirlineDao created in earlier post. Notice the @WebService(endpointInterface = "") which tells that this implementation is for AirlineManager interface.


import javax.jws.WebService;

@WebService(endpointInterface = "")
public class AirlineManagerImpl implements AirlineManager {
private AirlineDao airlineDao;

public AirlineManagerImpl(AirlineDao aAirlineDao) {
airlineDao = aAirlineDao;

public void create(String code, String name) {
airlineDao.create(code, name);

Add this in the spring-context.xml. Here we are importing some cxf beans, defining bean AirlineManagerImpl and creating airlineManagerService webservice.

<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-extension-http-jetty.xml"/>
<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />

<bean id="airlineManager" class="">
<constructor-arg><ref bean="airlineDao"/></constructor-arg>

<jaxws:endpoint id="airlineManagerService" implementor="#airlineManager" address="/AirlineManagerService" />

Add this in your web.xml.

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


Deploy the application in tomcat and your webservice is ready. You can check the wsdl http://host:port/travel/AirlineManagerService?wsdl.

To test the webservice, you need to create a client. You can use wsdl2java available in the bin directory of cxf.

Execute this command, this will generate the wsdl stubs.
wsdl2java http://host:port/travel/AirlineManagerService?wsdl

Write a client like this and there you go.......


public class ClientTest {
public static void main(String[] args) {
AirlineManagerImplService service = new AirlineManagerImplService();
AirlineManager airlineManager = service.getAirlineManagerImplPort();
airlineManager.create("IC", "Indian");

1 comment:

  1. Hi I have copied your project exactly but for some reason its not working for me. I have deployed the war on glassfish and when I launch it , it gives me an http 503 status error, service not available. could you please help?thanks