CXF Restful Tutorial
CXF Restful Tutorial explains step by step details of Creating / Developing Java rest Web services using Apache CXF, Spring and Eclipse
JAX-RS is Java API for RESTful Webservices which is very rely upon Representational State Transfer model, you can view JAX-RS specification
JAX-RS uses annotations for simplifying the development efforts.
Now a days more & more deployment is going based on restful services compare to WSDL Webservices, due to the weights towards the simplicity of configuration
You can see the below example, which is demonstrating How to create a Restful service using CXF
Required Libraries
You need to download
Following jar must be in classpath
- commons-logging-1.1.1.jar
- cxf-2.7.3.jar
- httpasyncclient-4.0-beta3.jar
- httpclient-4.2.1.jar
- httpcore-4.2.2.jar
- httpcore-nio-4.2.2.jar
- neethi-3.0.2.jar
- spring-aop-3.0.7.RELEASE.jar
- spring-asm-3.0.7.RELEASE.jar
- spring-beans-3.0.7.RELEASE.jar
- spring-context-3.0.7.RELEASE.jar
- spring-core-3.0.7.RELEASE.jar
- spring-expression-3.0.7.RELEASE.jar
- spring-web-3.0.7.RELEASE.jar
- wsdl4j-1.6.2.jar
- jaxb-impl-2.2.6.jar
- javax.ws.rs-api-2.0-m10.jar
- xmlschema-core-2.0.3.jar
- jettison-1.3.3.jar (JSON library)
CXF Restful Tutorial
I am creating a sample restful service project that pass Student object and return with some changes on that object. The service is using simple POJO (Plain Old Java Object) bean.
Firstly create a Dynamic Web Project (File->New->Dynamic Web Project) named "CXFRestfulTutorial" according to following screenshot

Create a Student Object
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "Student")
public class Student {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Here @XmlRootElement(name = "Student"), is a JAXB convension specifies that Student is XML document.
If you are specifies that @Produces("application/json") then Jettison library converts the JAXB to json text as response
Create a Service Interface
This service interface will defines which methods of restful service, to be invoked by the client
public interface ChangeStudentDetails {
Student changeName(Student student);
Student getName();
}
Implement the Service Interface
Here we implment the service interface created on the previous step
Here we are using one example showing with GET method& another with POST method
GET---> Calling this method will not result any changes to the server
POST---> Calling this method will result changes to the server, This have more secure than GET method
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
@Consumes("application/json")
@Produces("application/json")
public class ChangeStudentDetailsImpl implements ChangeStudentDetails {
@POST
@Path("/changeName")
public Student changeName(Student student) {
student.setName("HELLO " + student.getName());
return student;
}
@GET
@Path("/getName")
public Student getName() {
Student student = new Student();
student.setName("Rockey");
return student;
}
}
Note; On the above ChangeStudentDetailsImpl class, implementing an interface is not necessity, you can create restful services without implementing an interface.
@Consumes annotation specifies, the request is coming from the client
you can specify the Mime type as @Consumes("application/xml"), if the request is in xml format
@Produces annotation specifies, the response is going to the client
you can specify the Mime type as @Produces ("application/xml"), if the response need to be in xml format
Create a cxf.xml
CXF is using Spring internally, Finding classes by spring we need to add service implementation beans are added on "jaxrs:serviceBeans".
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jaxrs="http://cxf.apache.org/jaxrs" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd"> <import resource="classpath:META-INF/cxf/cxf.xml" /> <jaxrs:server id="base" address="/rest"> <jaxrs:serviceBeans> <ref bean="StudentService" /> </jaxrs:serviceBeans> </jaxrs:server> <bean id="StudentService" class="com.student.ChangeStudentDetailsImpl" /> </beans>
Change web.xml
Change the web.xml file to find CXF servlet and cxf.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <context-param> <param-name>contextConfigLocation</param-name> <param-value>WEB-INF/cxf.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <servlet> <servlet-name>CXFServlet</servlet-name> <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>CXFServlet</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> </web-app>
Publishing CXF Restful Service

Deployed REST Web Service Using CXF

to admin I also have same problem like Julien. would you please tell me how to do ? 18-Apr-2013 09:24:53 org.apache.catalina.core.AprLifecycleListener init INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jdk1.6.0_17\bin;.;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/Program Files/Java/jre7/bin/client;C:/Program Files/Java/jre7/bin;C:/Program Files/Java/jre7/lib/i386;C:\XEClient\bin;C:\Program Files\Common Files\Microsoft Shared\Windows Live;C:\Program Files\Intel\iCLS Client\;C:\Program Files\AMD APP\bin\x86;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Program Files\ATI Technologies\ATI.ACE\Core-Static;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Common Files\Lenovo;C:\Program Files\Windows Live\Shared;C:\SWTOOLS\ReadyApps;C:\Program Files\Gemalto\Classic Client\BIN;C:\Program Files\TortoiseSVN\bin;D:\eclipse; 18-Apr-2013 09:24:53 org.apache.tomcat.util.digester.SetPropertiesRule begin WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:CXFRestfulTutorial' did not find a matching property. 18-Apr-2013 09:24:53 org.apache.coyote.AbstractProtocol init INFO: Initializing ProtocolHandler ["http-bio-8080"] 18-Apr-2013 09:24:53 org.apache.coyote.AbstractProtocol init INFO: Initializing ProtocolHandler ["ajp-bio-8009"] 18-Apr-2013 09:24:53 org.apache.catalina.startup.Catalina load INFO: Initialization processed in 246 ms 18-Apr-2013 09:24:53 org.apache.catalina.core.StandardService startInternal INFO: Starting service Catalina 18-Apr-2013 09:24:53 org.apache.catalina.core.StandardEngine startInternal INFO: Starting Servlet Engine: Apache Tomcat/7.0.37 18-Apr-2013 09:24:54 org.apache.catalina.loader.WebappClassLoader validateJarFile INFO: validateJarFile(D:\eclipse\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps\CXFRestfulTutorial\WEB-INF\lib\geronimo-servlet_3.0_spec-1.0.jar) - jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class 18-Apr-2013 09:24:55 org.apache.catalina.core.ApplicationContext log INFO: Initializing Spring root WebApplicationContext 18-Apr-2013 09:24:55 org.springframework.web.context.ContextLoader initWebApplicationContext INFO: Root WebApplicationContext: initialization started 18-Apr-2013 09:24:55 org.springframework.context.support.AbstractApplicationContext prepareRefresh INFO: Refreshing Root WebApplicationContext: startup date [Thu Apr 18 09:24:55 CST 2013]; root of context hierarchy 18-Apr-2013 09:24:55 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/cxf.xml] 18-Apr-2013 09:24:55 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions INFO: Loading XML bean definitions from class path resource [META-INF/cxf/cxf.xml] 18-Apr-2013 09:24:55 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@ee260b: defining beans [cxf,org.apache.cxf.bus.spring.BusWiringBeanFactoryPostProcessor,org.apache.cxf.bus.spring.Jsr250BeanPostProcessor,org.apache.cxf.bus.spring.BusExtensionPostProcessor,base,StudentService]; root of factory hierarchy 18-Apr-2013 09:24:56 org.apache.cxf.endpoint.ServerImpl initDestination INFO: Setting the server's publish address to be /rest 18-Apr-2013 09:24:56 org.apache.cxf.service.factory.ReflectionServiceFactoryBean buildServiceFromWSDL INFO: Creating Service {http://docs.oasis-open.org/ws-dd/ns/discovery/2009/01}Discovery from WSDL: classpath:/org/apache/cxf/ws/discovery/wsdl/wsdd-discovery-1.1-wsdl-os.wsdl 18-Apr-2013 09:24:56 org.apache.cxf.endpoint.ServerImpl initDestination INFO: Setting the server's publish address to be soap.udp://239.255.255.250:3702 18-Apr-2013 09:24:56 org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons INFO: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@ee260b: defining beans [cxf,org.apache.cxf.bus.spring.BusWiringBeanFactoryPostProcessor,org.apache.cxf.bus.spring.Jsr250BeanPostProcessor,org.apache.cxf.bus.spring.BusExtensionPostProcessor,base,StudentService]; root of factory hierarchy 18-Apr-2013 09:24:56 org.springframework.web.context.ContextLoader initWebApplicationContext SEVERE: Context initialization failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'base': Invocation of init method failed; nested exception is org.apache.cxf.service.factory.ServiceConstructionException at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1422) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:518) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:455) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:192) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425) at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:282) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:204) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4797) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5291) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549) at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303) at java.util.concurrent.FutureTask.run(FutureTask.java:138) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:619) Caused by: org.apache.cxf.service.factory.ServiceConstructionException at org.apache.cxf.jaxrs.JAXRSServerFactoryBean.create(JAXRSServerFactoryBean.java:201) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeCustomInitMethod(AbstractAutowireCapableBeanFactory.java:1546) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1487) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1419) ... 22 more Caused by: java.lang.NullPointerException at org.apache.cxf.ws.discovery.internal.WSDiscoveryServiceImpl.serverStarted(WSDiscoveryServiceImpl.java:126) at org.apache.cxf.ws.discovery.listeners.WSDiscoveryServerListener.startServer(WSDiscoveryServerListener.java:72) at org.apache.cxf.bus.managers.ServerLifeCycleManagerImpl.startServer(ServerLifeCycleManagerImpl.java:61) at org.apache.cxf.endpoint.ServerImpl.start(ServerImpl.java:146) at org.apache.cxf.jaxrs.JAXRSServerFactoryBean.create(JAXRSServerFactoryBean.java:192) ... 29 more 18-Apr-2013 09:24:56 org.apache.catalina.core.StandardContext listenerStart SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'base': Invocation of init method failed; nested exception is org.apache.cxf.service.factory.ServiceConstructionException at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1422) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:518) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:455) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:192) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425) at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:282) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:204) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4797) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5291) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559) at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549) at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303) at java.util.concurrent.FutureTask.run(FutureTask.java:138) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:619) Caused by: org.apache.cxf.service.factory.ServiceConstructionException at org.apache.cxf.jaxrs.JAXRSServerFactoryBean.create(JAXRSServerFactoryBean.java:201) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeCustomInitMethod(AbstractAutowireCapableBeanFactory.java:1546) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1487) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1419) ... 22 more Caused by: java.lang.NullPointerException at org.apache.cxf.ws.discovery.internal.WSDiscoveryServiceImpl.serverStarted(WSDiscoveryServiceImpl.java:126) at org.apache.cxf.ws.discovery.listeners.WSDiscoveryServerListener.startServer(WSDiscoveryServerListener.java:72) at org.apache.cxf.bus.managers.ServerLifeCycleManagerImpl.startServer(ServerLifeCycleManagerImpl.java:61) at org.apache.cxf.endpoint.ServerImpl.start(ServerImpl.java:146) at org.apache.cxf.jaxrs.JAXRSServerFactoryBean.create(JAXRSServerFactoryBean.java:192) ... 29 more 18-Apr-2013 09:24:56 org.apache.catalina.core.StandardContext startInternal SEVERE: Error listenerStart 18-Apr-2013 09:24:56 org.apache.catalina.core.StandardContext startInternal SEVERE: Context [/CXFRestfulTutorial] startup failed due to previous errors 18-Apr-2013 09:24:56 org.apache.catalina.core.ApplicationContext log INFO: Closing Spring root WebApplicationContext 18-Apr-2013 09:24:56 org.apache.catalina.loader.WebappClassLoader clearReferencesThreads SEVERE: The web application [/CXFRestfulTutorial] appears to have started a thread named [default-workqueue-1] but has failed to stop it. This is very likely to create a memory leak. 18-Apr-2013 09:24:56 org.apache.catalina.loader.WebappClassLoader checkThreadLocalMapForLeaks SEVERE: The web application [/CXFRestfulTutorial] created a ThreadLocal with key of type [com.sun.xml.bind.v2.ClassFactory$1] (value [com.sun.xml.bind.v2.ClassFactory$1@1927275]) and a value of type [java.util.WeakHashMap] (value [{class javax.xml.bind.annotation.W3CDomHandler=java.lang.ref.WeakReference@1987298}]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak. 18-Apr-2013 09:24:56 org.apache.coyote.AbstractProtocol start INFO: Starting ProtocolHandler ["http-bio-8080"] 18-Apr-2013 09:24:56 org.apache.coyote.AbstractProtocol start INFO: Starting ProtocolHandler ["ajp-bio-8009"] 18-Apr-2013 09:24:56 org.apache.catalina.startup.Catalina start INFO: Server startup in 2904 ms