Jersey + Spring integration example

This tutorial show you how to integrate Jersey web application with Spring framework.

Technologies used :

  1. Jersey 1.8
  2. Spring 3.0.5.RELEASE
  3. Eclipse 3.6
  4. Maven 3

1. Project Dependency

Declares Jersey 1.8, Spring3 and “jersey-spring.jar” dependencies in Maven pom.xml file.

Note
In “jersey-spring.jar” version, it will download all the Spring 2.5.6 dependencies. To use Spring 3, you need to exclude those old Spring libraries manually.
	<repositories>
		<repository>
			<id>maven2-repository.java.net</id>
			<name>Java.net Repository for Maven</name>
			<url>http://download.java.net/maven/2/</url>
		</repository>
	</repositories>
 
	<dependencies>
 
		<!-- Jersey -->
		<dependency>
			<groupId>com.sun.jersey</groupId>
			<artifactId>jersey-server</artifactId>
			<version>1.8</version>
		</dependency>
 
		<!-- Spring 3 dependencies -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>3.0.5.RELEASE</version>
		</dependency>
 
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>3.0.5.RELEASE</version>
		</dependency>
 
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>3.0.5.RELEASE</version>
		</dependency>
 
		<!-- Jersey + Spring -->
		<dependency>
			<groupId>com.sun.jersey.contribs</groupId>
			<artifactId>jersey-spring</artifactId>
			<version>1.8</version>
			<exclusions>
				<exclusion>
					<groupId>org.springframework</groupId>
					<artifactId>spring</artifactId>
				</exclusion>
				<exclusion>
					<groupId>org.springframework</groupId>
					<artifactId>spring-core</artifactId>
				</exclusion>
				<exclusion>
					<groupId>org.springframework</groupId>
					<artifactId>spring-web</artifactId>
				</exclusion>
				<exclusion>
					<groupId>org.springframework</groupId>
					<artifactId>spring-beans</artifactId>
				</exclusion>
				<exclusion>
					<groupId>org.springframework</groupId>
					<artifactId>spring-context</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
 
	</dependencies>

2. Spring Bean

A simple “transactionBo” bean is registered in Spring Ioc container. Later you will inject this bean into Jersey service.

package com.mkyong.transaction;
 
public interface TransactionBo{
 
	String save();
 
}
package com.mkyong.transaction.impl;
 
import com.mkyong.transaction.TransactionBo;
 
public class TransactionBoImpl implements TransactionBo {
 
	public String save() {
 
		return "Jersey + Spring example";
 
	}
 
}

File : applicationContext.xml – Register bean and enable the component auto scanning feature.

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context-3.0.xsd">
 
	<context:component-scan base-package="com.mkyong.rest" />
 
        <bean id="transactionBo" 
                  class="com.mkyong.transaction.impl.TransactionBoImpl" />
 
</beans>

3. Jersey

In REST method, you can to auto inject the “transactionBo” bean from Spring into Jersey.

package com.mkyong.rest;
 
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.mkyong.transaction.TransactionBo;
 
@Component
@Path("/payment")
public class PaymentService {
 
	@Autowired
	TransactionBo transactionBo;
 
	@GET
	@Path("/mkyong")
	public Response savePayment() {
 
		String result = transactionBo.save();
 
		return Response.status(200).entity(result).build();
 
	}
 
}

4. Integrate Jersey with Spring

The core integration is in web.xml

  1. Register Spring “ContextLoaderListener” listener class
  2. Change Jersey servlet from “com.sun.jersey.spi.container.servlet.ServletContainer” to “com.sun.jersey.spi.spring.container.servlet.SpringServlet“.

File : web.xml

<web-app id="WebApp_ID" version="2.4"
	xmlns="http://java.sun.com/xml/ns/j2ee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
	<display-name>Restful Web Application</display-name>
 
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext.xml</param-value>
	</context-param>
 
	<listener>
		<listener-class>
			org.springframework.web.context.ContextLoaderListener
		</listener-class>
	</listener>
 
	<servlet>
		<servlet-name>jersey-serlvet</servlet-name>
		<servlet-class>
			com.sun.jersey.spi.spring.container.servlet.SpringServlet
		</servlet-class>
		<init-param>
			<param-name>
                                 com.sun.jersey.config.property.packages
                        </param-name>
			<param-value>com.mkyong.rest</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
 
	<servlet-mapping>
		<servlet-name>jersey-serlvet</servlet-name>
		<url-pattern>/rest/*</url-pattern>
	</servlet-mapping>
 
</web-app>

5. Demo

jersey spring demo

Download Source Code

References

  1. Jersey Spring JavaDoc
  2. Spring 3 in Jersey
  3. Spring auto component scanning
  4. RESTEasy + Spring integration example
Tags :

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

  • Pingback: watch movies online free()

  • Pingback: streaming movies()

  • Pingback: watch movies online()

  • Pingback: Blue Coaster33()

  • Pingback: JAX-RS TUTORIALS | BUYWORKSELL()

  • Karthik

    Hi…After implementing jersey with spring my application I am getting a null pointer exception for autowired class

    Nov 03, 2013 11:58:03 AM org.glassfish.jersey.server.ServerRuntime$Responder mapException
    WARNING: WebApplicationException cause:
    java.lang.NullPointerException
    at com.hyd.telos.MyResource.getIt(MyResource.java:33)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory$1.invoke(ResourceMethodInvocationHandlerFactory.java:81)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:151)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:171)
    at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:152)
    at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:104)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:367)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:349)
    at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:106)
    at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:259)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
    at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
    at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
    at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:318)
    at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:236)
    at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:983)
    at org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpContainer.service(GrizzlyHttpContainer.java:334)
    at org.glassfish.grizzly.http.server.HttpHandler$1.run(HttpHandler.java:209)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:565)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545)
    at java.lang.Thread.run(Thread.java:722)

  • basavaraj

    Hi,

    i am using the same above application for testing like how to create jersey webservice
    but i am getting below error

    SEVERE: A child container failed during start
    java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/JerseyWebservice]]
    at java.util.concurrent.FutureTask$Sync.innerGet(Unknown Source)
    at java.util.concurrent.FutureTask.get(Unknown Source)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1123)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:800)
    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(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
    Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/JerseyWebservice]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    … 7 more
    Caused by: java.lang.NoClassDefFoundError: com/sun/jersey/spi/service/ComponentProvider
    at java.lang.Class.getDeclaredFields0(Native Method)
    at java.lang.Class.privateGetDeclaredFields(Unknown Source)
    at java.lang.Class.getDeclaredFields(Unknown Source)
    at org.apache.catalina.util.Introspection.getDeclaredFields(Introspection.java:106)
    at org.apache.catalina.startup.WebAnnotationSet.loadFieldsAnnotation(WebAnnotationSet.java:261)
    at org.apache.catalina.startup.WebAnnotationSet.loadApplicationServletAnnotations(WebAnnotationSet.java:140)
    at org.apache.catalina.startup.WebAnnotationSet.loadApplicationAnnotations(WebAnnotationSet.java:67)
    at org.apache.catalina.startup.ContextConfig.applicationAnnotationsConfig(ContextConfig.java:405)
    at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:881)
    at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:369)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
    at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5179)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    … 7 more
    Caused by: java.lang.ClassNotFoundException: com.sun.jersey.spi.service.ComponentProvider
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1714)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1559)
    … 21 more

    Oct 14, 2013 12:16:51 AM org.apache.catalina.core.ContainerBase startInternal
    SEVERE: A child container failed during start
    java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
    at java.util.concurrent.FutureTask$Sync.innerGet(Unknown Source)
    at java.util.concurrent.FutureTask.get(Unknown Source)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1123)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:302)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:443)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:732)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:684)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:322)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:456)
    Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    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(Unknown Source)
    at java.util.concurrent.FutureTask.run(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)
    Caused by: org.apache.catalina.LifecycleException: A child container failed during start
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1131)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:800)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    … 7 more

    Oct 14, 2013 12:16:51 AM org.apache.catalina.startup.Catalina start
    SEVERE: Catalina.start:
    org.apache.catalina.LifecycleException: Failed to start component [StandardServer[8005]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:684)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:322)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:456)
    Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardService[Catalina]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:732)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    … 7 more
    Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    at org.apache.catalina.core.StandardService.startInternal(StandardService.java:443)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    … 9 more
    Caused by: org.apache.catalina.LifecycleException: A child container failed during start
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1131)
    at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:302)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    … 11 more

    Oct 14, 2013 12:16:51 AM org.apache.catalina.startup.Catalina start
    INFO: Server startup in 3031 ms

    PLease help me out on this what i am missing

  • Dave

    Hi,

    I’m trying to get this working only without using xml configuration. I’m using Jersey/Tomcat/Spring/Maven. That being said, I’m having a problem getting my autowired attribute. If you have the chance, could you take a look?

    Here are the full details:

    http://stackoverflow.com/questions/19302445/unable-to-get-autowired-to-work-or-do-a-component-scan

  • Abhi

    Inject is not working for above code

  • Raghunath

    Hello Yong Sir,

    We are very much interested in your applications and thanks so much for the same.

    Raghunath.

  • Anonymous

    need another exclusion (spring-aop)

  • Arun

    Hi,

    Everything works fine for me except loading the values from property file for SpringContextLoaderListener. I am getting the below the exception

    <User defined listener org.jboss.resteasy.plugins.spring.SpringContextLoaderListener failed: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dropDownDataSource' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Invocation of init method failed; nested exception is javax.naming.NoInitialContextException: Cannot instantiate class: ${datasource.java.naming.factory.initial} [Root exception is java.lang.ClassNotFoundException: ${datasource.java.naming.factory.initial}].
    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dropDownDataSource' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Invocation of init method failed; nested exception is javax.naming.NoInitialContextException: Cannot instantiate class: ${datasource.java.naming.factory.initial} [Root exception is java.lang.ClassNotFoundException: ${datasource.java.naming.factory.initial}]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1412)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    Truncated. see log file for complete stacktrace

    where ${datasource.java.naming.factory.initial} is value which i am getting from a property file. let me know what i have done wrong here

  • Pradip Bhatt

    Hello mkyong..

    Thanks for this post.
    I use struts2 + spring3 + hibernate for my application. I have implementing Jersey successfully. Now whenever i call the service at that time following error is occured.

    [LazyInitializationException:110] failed to lazily initialize a collection of role:
    no session or session was closed

    org.codehaus.jackson.map.JsonMappingException: failed to lazily initialize a collection of role: com.aspire.hrms.model.OrganizationGeneralInfo.users, no session or session was closed (through reference chain: java.util.ArrayList[0]->com.aspire.hrms.model.Department[“organization”]->com.aspire.hrms.model.OrganizationGeneralInfo[“users”])

  • Pratik Palkar

    Hi mkyong,

    What is the use of the line ‘Response.status(200).entity(result).build()’ in above application?

  • Kiran

    Hi mkyong,
    can I please suggest me how to integrate REST using Spring HessianServiceExporter

  • Lester

    Hi Mr. Yong,

    Could you give an example how to integrate Jersey test framework with this example. I am using this example with MYSQL, Spring JDBC and Tomcat. But I can not make unit test working with configuration problems. I use this library.

            &lt;dependency&gt;
    			&lt;groupId&gt;com.sun.jersey.jersey-test-framework&lt;/groupId&gt;
    			&lt;artifactId&gt;jersey-test-framework-grizzly2&lt;/artifactId&gt;
    			&lt;version&gt;${jersey.version}&lt;/version&gt;
    			&lt;scope&gt;test&lt;/scope&gt;
    		&lt;/dependency&gt;

    Many thanks.

  • mahesh

    I am getting the error

     SEVERE: Context initialization failed
    org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [com.bnymellon.touchpoint.controller.TransactionBO] for bean with name 'BO' defined in ServletContext resource [/applicationContext.xml]; nested exception is java.lang.ClassNotFoundException: com.bnymellon.touchpoint.controller.TransactionBO
    	at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1250)
    	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.predictBeanType(AbstractAutowireCapableBeanFactory.java:576)
    	at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:1319)
    	at org.springframework.beans.factory.support.AbstractBeanFactory.isFactoryBean(AbstractBeanFactory.java:885)
    	at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:562)
    	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:276)
    	at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:197)
    	at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47)
    	at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4723)
    	at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5226)
    	at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5221)
    	at java.util.concurrent.FutureTask$Sync.innerRun(Unknown Source)
    	at java.util.concurrent.FutureTask.run(Unknown Source)
    	at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    	at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    	at java.lang.Thread.run(Unknown Source)
    Caused by: java.lang.ClassNotFoundException: com.bnymellon.touchpoint.controller.TransactionBO
    	at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1676)
    	at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1521)
    	at org.springframework.util.ClassUtils.forName(ClassUtils.java:257)
    	at org.springframework.beans.factory.support.AbstractBeanDefinition.resolveBeanClass(AbstractBeanDefinition.java:408)
    	at org.springframework.beans.factory.support.AbstractBeanFactory.doResolveBeanClass(AbstractBeanFactory.java:1271)
    	at org.springframework.beans.factory.support.AbstractBeanFactory.resolveBeanClass(AbstractBeanFactory.java:1242)
    	... 17 more
     
    Jan 11, 2013 2:06:16 PM org.apache.catalina.core.StandardContext listenerStart
    • mahesh

      The bean isnot getting instanciated. Please let me know

  • http://jfx.cz Felix

    Hi, thx for tutorial. I have to fix my POM.xml with this..

                            &lt;exclusion&gt;
                                &lt;artifactId&gt;spring-aop&lt;/artifactId&gt;
                                &lt;groupId&gt;org.springframework&lt;/groupId&gt;
                            &lt;/exclusion&gt;
  • kasav

    Hi mkyong,

    Will you please include a spring-jersey-jpa-hibernate blog on your site? I can’t find any working example on the internet.

  • ahmed

    hi i am using hersey + spring and JAXB annotation
    i have annotated all my model classes and the controler layer is my WS where i ve pouted WS annotation
    so i’ve got this messages ;

    GRAVE: A message body writer for Java class com.alpha.vconf.model.Reunion_$$_javassist_3, and Java type class com.alpha.vconf.model.Reunion, and MIME media type application/xml was not found
    27 déc. 2012 14:19:27 com.sun.jersey.spi.container.ContainerResponse write
    GRAVE: The registered message body writers compatible with the MIME media type are:
    application/xml -&gt;
      com.sun.jersey.core.impl.provider.entity.XMLJAXBElementProvider$App
      com.sun.jersey.core.impl.provider.entity.DocumentProvider
      com.sun.jersey.core.impl.provider.entity.SourceProvider$SourceWriter
      com.sun.jersey.core.impl.provider.entity.XMLRootElementProvider$App
      com.sun.jersey.core.impl.provider.entity.XMLListElementProvider$App
    */* -&gt;
      com.sun.jersey.core.impl.provider.entity.FormProvider
      com.sun.jersey.core.impl.provider.entity.MimeMultipartProvider
      com.sun.jersey.core.impl.provider.entity.StringProvider
      com.sun.jersey.core.impl.provider.entity.ByteArrayProvider
      com.sun.jersey.core.impl.provider.entity.FileProvider
      com.sun.jersey.core.impl.provider.entity.InputStreamProvider
      com.sun.jersey.core.impl.provider.entity.DataSourceProvider
      com.sun.jersey.core.impl.provider.entity.XMLJAXBElementProvider$General
      com.sun.jersey.core.impl.provider.entity.ReaderProvider
      com.sun.jersey.core.impl.provider.entity.DocumentProvider
      com.sun.jersey.core.impl.provider.entity.StreamingOutputProvider
      com.sun.jersey.core.impl.provider.entity.SourceProvider$SourceWriter
      com.sun.jersey.json.impl.provider.entity.JSONJAXBElementProvider$General
      com.sun.jersey.json.impl.provider.entity.JSONArrayProvider$General
      com.sun.jersey.json.impl.provider.entity.JSONObjectProvider$General
      com.sun.jersey.json.impl.provider.entity.JSONWithPaddingProvider
      com.sun.jersey.server.impl.template.ViewableMessageBodyWriter
      com.sun.jersey.core.impl.provider.entity.XMLRootElementProvider$General
      com.sun.jersey.core.impl.provider.entity.XMLListElementProvider$General
      com.sun.jersey.json.impl.provider.entity.JSONRootElementProvider$General
      com.sun.jersey.json.impl.provider.entity.JSONListElementProvider$General
      com.sun.jersey.json.impl.provider.entity.JacksonProviderProxy
     
    27 déc. 2012 14:19:27 com.sun.jersey.spi.container.ContainerResponse logException
    GRAVE: Mapped exception to response: 500 (Internal Server Error)
    javax.ws.rs.WebApplicationException: com.sun.jersey.api.MessageException: A message body writer for Java class com.alpha.vconf.model.Reunion_$$_javassist_3, and Java type class com.alpha.vconf.model.Reunion, and MIME media type application/xml was not found
    	at com.sun.jersey.spi.container.ContainerResponse.write(ContainerResponse.java:285)
    	at com.sun.jersey.server.impl.application.WebApplicationImpl._handleRequest(WebApplicationImpl.java:1479)
    	at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1391)
    	at com.sun.jersey.server.impl.application.WebApplicationImpl.handleRequest(WebApplicationImpl.java:1381)
    	at com.sun.jersey.spi.container.servlet.WebComponent.service(WebComponent.java:416)
    	at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:538)
    	at com.sun.jersey.spi.container.servlet.ServletContainer.service(ServletContainer.java:716)
    	at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
    	at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)
    	at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:602)
    	at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    	at java.lang.Thread.run(Thread.java:662)
    Caused by: com.sun.jersey.api.MessageException: A message body writer for Java class com.alpha.vconf.model.Reunion_$$_javassist_3, and Java type class com.alpha.vconf.model.Reunion, and MIME media type application/xml was not found
    	... 20 more
    • ahmed

      the problem is solved ; all my configuration is OK , it was problem related to the that i used to get an entity by id , instead of using get i have used load accidently

  • SRI

    I followed the steps.I am using embedded jetty server and it’s not starting when i change servlet class name from
    com.sun.jersey.spi.container.servlet.ServletContainer
    to
    com.sun.jersey.spi.spring.container.servlet.SpringServlet

  • giri

    sir,

    1)we can use org.springframework.web.servlet.DispatcherServlet And com.sun.jersey.spi.spring.container.servlet.SpringServlet in a single Web.xml file ?

    2)i am using both in a single web.xml file and some times it is working fine and some times not working the code. it is giving error like context initialization failed when i first start the application

    3)My Web.xml file is

     &lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
    &lt;web-app id=&quot;WebApp_ID&quot; version=&quot;2.4&quot; xmlns=&quot;http://java.sun.com/xml/ns/j2ee&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation=&quot;http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd&quot;&gt;
    	&lt;welcome-file-list&gt;
    	&lt;welcome-file&gt;krams/main/persons/&lt;/welcome-file&gt;
    	&lt;/welcome-file-list&gt;
     
    	&lt;listener&gt;
    		&lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt;
    	&lt;/listener&gt;
    	&lt;servlet&gt;
    		&lt;servlet-name&gt;spring1&lt;/servlet-name&gt;
    		&lt;servlet-class&gt;com.sun.jersey.spi.spring.container.servlet.SpringServlet&lt;/servlet-class&gt;
    		&lt;!--&lt;init-param&gt;
    			&lt;param-name&gt;
                                     com.sun.jersey.config.property.packages
                            &lt;/param-name&gt;
    			&lt;param-value&gt;org.krams.tutorial.service&lt;/param-value&gt;
    		&lt;/init-param&gt;
    		--&gt;&lt;load-on-startup&gt;2&lt;/load-on-startup&gt;
    	&lt;/servlet&gt;
     
    	&lt;servlet-mapping&gt;
    		&lt;servlet-name&gt;spring1&lt;/servlet-name&gt;
    		&lt;url-pattern&gt;/webser/*&lt;/url-pattern&gt;
    	&lt;/servlet-mapping&gt;
     
     
    &lt;servlet&gt;
    		&lt;servlet-name&gt;spring&lt;/servlet-name&gt;
    		&lt;servlet-class&gt;org.springframework.web.servlet.DispatcherServlet&lt;/servlet-class&gt;
     
    		&lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
    	&lt;/servlet&gt;
     
    	&lt;servlet-mapping&gt;
    		&lt;servlet-name&gt;spring&lt;/servlet-name&gt;
    		&lt;url-pattern&gt;/krams/*&lt;/url-pattern&gt;
    	&lt;/servlet-mapping&gt;
     
     
    &lt;/web-app&gt;
  • giri

    sir,
    in which layer implementation is best for Web services(jersey) in Springs like 1)controller layer
    2)service layer?.

    • http://www.mkyong.com mkyong

      Depends on your system requirement, web service can be implemented in both layers.

      • giri

        sir,
        previously i am not using Jersey web service in my Spring applicatio, now i am using jersey web service in my app.what problem i am faceing now is previous my code is not working(i.e controllers to view), only web service code is working(i.e i copied your PaymentService class in my service layer only that class is accesible right now)

        http://localhost:8080/spring-hibernate-mysql/krams/main/persons => my previous controller

        giving Error like : java.lang.StringIndexOutOfBoundsException: String index out of range: -6

        BUT

        http://giri-pc:8080/spring-hibernate-mysql/krams/payment/mkyong

        dISPLAYING lIKE THIS “Jersey + Spring example

        Previous Web.xml File

        pre lang=”xml”>

        spring
        org.springframework.web.servlet.DispatcherServlet
        1

        spring
        /krams/*

        org.springframework.web.context.ContextLoaderListener

        After Integrating Jersey Web.xml

        	&lt;listener&gt;
        		&lt;listener-class&gt;org.springframework.web.context.ContextLoaderListener&lt;/listener-class&gt;
        	&lt;/listener&gt;
        	&lt;servlet&gt;
        		&lt;servlet-name&gt;spring&lt;/servlet-name&gt;
        		&lt;servlet-class&gt;com.sun.jersey.spi.spring.container.servlet.SpringServlet&lt;/servlet-class&gt;
        		&lt;init-param&gt;
        			&lt;param-name&gt;
                                         com.sun.jersey.config.property.packages
                                &lt;/param-name&gt;
        			&lt;param-value&gt;com.mkyong.rest&lt;/param-value&gt;
        		&lt;/init-param&gt;
        		&lt;load-on-startup&gt;1&lt;/load-on-startup&gt;
        	&lt;/servlet&gt;
         
        	&lt;servlet-mapping&gt;
        		&lt;servlet-name&gt;spring&lt;/servlet-name&gt;
        		&lt;url-pattern&gt;/krams/*&lt;/url-pattern&gt;
        	&lt;/servlet-mapping&gt;
  • amar

    Thank you very much, you helped me in entire project through your blogs.

  • kavya

    Hi, when after importing the project, when i am running i am getting this exception. Please help me to resolve this.

    java.lang.NoClassDefFoundError: org/springframework/aop/support/AopUtils
    at com.sun.jersey.spi.spring.container.SpringComponentProviderFactory.getInjectableInstance(SpringComponentProviderFactory.java:240)

    • Venkat

      I am also getting the same error.

  • Pawan

    HI,

    I am using the Jersey+spring in my Project.

    My problem is that,
    If Some properties in my POJO is null, then these properties also being converted in JSON having value as null.

    JSON Response:
    {
    “responseStatus”:”Success”,
    “name”:”Anthony”,
    “company”:null,
    “address” : null
    }

    How to avoid sending null property in the JSON response to UI.

    I have the Dependency mentioned in this example in POM, and Declared the POJOMappingFeature in Web.xml too.

    Please help

  • http://www.gettingcirrius.com Richard Clayton

    Thank you so much. Great tutorial. I’ve used the same example with Spring 3.1.1 and it works great.

  • Slash

    You made my day bro!

  • Balaji

    No need to exclude old spring libraries manually. You can configure POM.xml with exclusions. The list is missing spring-aop please modify the section to include below
    section

                                       &lt;exclusion&gt;
    					&lt;groupId&gt;org.springframework&lt;/groupId&gt;
    					&lt;artifactId&gt;spring-aop&lt;/artifactId&gt;
    				&lt;/exclusion&gt;
  • Oussama

    Thanks man you saved my day thanks a lot :)

  • Jeets

    I am also getting the same ASM library error.I upgraded the jar from 2.2 to 3.1 and it worked fine.But I doubt it may break the Spring code because 2.2 version of asm was dependency of Spring 2.5 which I am using.
    Is asm 3.1 compatible with Spring 2.5?

    • Jeets

      I am using Jersey1.8 with Spring.Jersey requires asm 3.1.

  • Mahesh Kandpal

    Hi Mkyong,
    For deploying in Tomcat 6 we need to specify the context file location as follows.

     
         contextConfigLocation
         classpath*:**/*Context.xml

    Please update the source code for others, thanks!

  • rahman usta

    i’ve got this messages ;

    19.Oca.2012 02:00:22 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 (x86)\Java\jdk1.6.0_27\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:\Program Files\ARM-RDVS\bin\win_32-pentium;C:\PHP\;C:\Program Files\Common Files\Microsoft Shared\Windows Live;C:\Program Files (x86)\Common Files\Microsoft Shared\Windows Live;C:\Program Files\ARM\bin\win_32-pentium;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;D:\gradle-1.0-milestone-3\bin;C:\Program Files (x86)\Java\jdk1.6.0_27\bin;D:\apache-ant-1.8.2\bin;C:\Program Files (x86)\glassfish3\glassfish\bin;D:\apache-maven-3.0.3\bin;C:\Program Files (x86)\Autodesk\Backburner\;C:\Program Files\Common Files\Autodesk Shared\;C:\Program Files (x86)\Heroku;C:\Program Files (x86)\git\bin;C:\Program Files (x86)\git\cmd;C:\Program Files (x86)\VisualSVN\bin;C:\Program Files (x86)\QuickTime\QTSystem\;C:\Program Files (x86)\MySQL\MySQL Server 5.1\bin;D:\curl;C:\Program Files (x86)\Calibre2\;C:\Keil\ARM\BIN40;C:\Program Files\ARM\RVI\Tools\3.3\106\programs\win_32-pentium;C:\Program Files\ARM\Utilities\FLEXlm\10.8.5.0\1\win_32-pentium;C:\Program Files\ARM\RVCT\Programs\4.0\400\win_32-pentium;C:\Program Files\ARM-RDVS\RVD\Core\4.0\1106\win_32-pentium\bin;C:\Program Files\ARM\RVD\Core\4.0\1106\win_32-pentium\bin;C:\Program Files\ARM\RVI\GDB\3.3\8;C:\Program Files (x86)\Windows Live\Shared;D:\appengine-java-sdk-1.6.1\bin;C:\Program Files (x86)\WinSCP\;C:\Program Files\ARM-RDVS\RVCT\Programs\4.0\400\win_32-pentium;C:\Program Files\ARM-RDVS\RVI\Tools\3.3\106\programs\win_32-pentium;C:\Program Files\ARM-RDVS\Utilities\FLEXlm\10.8.5.0\1\win_32-pentium;C:\Program Files\ARM-RDVS\RVI\GDB\3.3\8;.
    19.Oca.2012 02:00:22 org.apache.tomcat.util.digester.SetPropertiesRule begin
    WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property ‘source’ to ‘org.eclipse.jst.j2ee.server:RESTfulExample’ did not find a matching property.
    19.Oca.2012 02:00:22 org.apache.coyote.http11.Http11Protocol init
    INFO: Initializing Coyote HTTP/1.1 on http-8080
    19.Oca.2012 02:00:22 org.apache.catalina.startup.Catalina load
    INFO: Initialization processed in 461 ms
    19.Oca.2012 02:00:23 org.apache.catalina.core.StandardService start
    INFO: Starting service Catalina
    19.Oca.2012 02:00:23 org.apache.catalina.core.StandardEngine start
    INFO: Starting Servlet Engine: Apache Tomcat/6.0.35
    19.Oca.2012 02:00:23 org.apache.catalina.core.ApplicationContext log
    INFO: Initializing Spring root WebApplicationContext
    19.Oca.2012 02:00:23 org.springframework.web.context.ContextLoader initWebApplicationContext
    INFO: Root WebApplicationContext: initialization started
    19.Oca.2012 02:00:23 org.springframework.context.support.AbstractApplicationContext prepareRefresh
    INFO: Refreshing Root WebApplicationContext: startup date [Thu Jan 19 02:00:23 VET 2012]; root of context hierarchy
    19.Oca.2012 02:00:23 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
    INFO: Loading XML bean definitions from class path resource [applicationContext.xml]
    19.Oca.2012 02:00:23 org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
    INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@18efaea: defining beans [paymentService,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,transactionBo]; root of factory hierarchy
    19.Oca.2012 02:00:23 org.springframework.web.context.ContextLoader initWebApplicationContext
    INFO: Root WebApplicationContext: initialization completed in 446 ms
    19.Oca.2012 02:00:23 com.sun.jersey.api.core.PackagesResourceConfig init
    INFO: Scanning for root resource and provider classes in the packages:
    com.mkyong.rest
    19.Oca.2012 02:00:23 com.sun.jersey.api.core.ScanningResourceConfig logClasses
    INFO: Root resource classes found:
    class com.mkyong.rest.PaymentService
    19.Oca.2012 02:00:23 com.sun.jersey.api.core.ScanningResourceConfig init
    INFO: No provider classes found.
    19.Oca.2012 02:00:23 com.sun.jersey.spi.spring.container.servlet.SpringServlet getContext
    INFO: Using default applicationContext
    19.Oca.2012 02:00:23 com.sun.jersey.spi.spring.container.SpringComponentProviderFactory registerSpringBeans
    INFO: Registering Spring bean, paymentService, of type com.mkyong.rest.PaymentService as a root resource class
    19.Oca.2012 02:00:23 com.sun.jersey.server.impl.application.WebApplicationImpl _initiate
    INFO: Initiating Jersey application, version ‘Jersey: 1.8 06/24/2011 12:17 PM’
    19.Oca.2012 02:00:24 org.apache.catalina.core.ApplicationContext log
    SEVERE: StandardWrapper.Throwable
    java.lang.NoClassDefFoundError: org/springframework/aop/support/AopUtils
    at com.sun.jersey.spi.spring.container.SpringComponentProviderFactory.getInjectableInstance(SpringComponentProviderFactory.java:240)
    at com.sun.jersey.spi.spring.container.SpringComponentProviderFactory.access$100(SpringComponentProviderFactory.java:81)
    at com.sun.jersey.spi.spring.container.SpringComponentProviderFactory$SpringManagedComponentProvider.getInjectableInstance(SpringComponentProviderFactory.java:230)
    at com.sun.jersey.server.impl.component.IoCResourceFactory$SingletonWrapper.init(IoCResourceFactory.java:179)
    at com.sun.jersey.server.impl.application.WebApplicationImpl$10.f(WebApplicationImpl.java:584)
    at com.sun.jersey.server.impl.application.WebApplicationImpl$10.f(WebApplicationImpl.java:581)
    at com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:193)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.getResourceComponentProvider(WebApplicationImpl.java:581)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.initiateResource(WebApplicationImpl.java:658)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.initiateResource(WebApplicationImpl.java:653)
    at com.sun.jersey.server.impl.application.RootResourceUriRules.(RootResourceUriRules.java:124)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._initiate(WebApplicationImpl.java:1298)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.access$700(WebApplicationImpl.java:169)
    at com.sun.jersey.server.impl.application.WebApplicationImpl$13.f(WebApplicationImpl.java:775)
    at com.sun.jersey.server.impl.application.WebApplicationImpl$13.f(WebApplicationImpl.java:771)
    at com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:193)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:771)
    at com.sun.jersey.spi.spring.container.servlet.SpringServlet.initiate(SpringServlet.java:117)
    at com.sun.jersey.spi.container.servlet.ServletContainer$InternalWebComponent.initiate(ServletContainer.java:318)
    at com.sun.jersey.spi.container.servlet.WebComponent.load(WebComponent.java:609)
    at com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:210)
    at com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:373)
    at com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:556)
    at javax.servlet.GenericServlet.init(GenericServlet.java:212)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1206)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1026)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4421)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4734)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
    at org.apache.catalina.core.StandardHost.start(StandardHost.java:840)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
    at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463)
    at org.apache.catalina.core.StandardService.start(StandardService.java:525)
    at org.apache.catalina.core.StandardServer.start(StandardServer.java:754)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:595)
    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.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
    Caused by: java.lang.ClassNotFoundException: org.springframework.aop.support.AopUtils
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1680)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1526)
    … 41 more
    19.Oca.2012 02:00:24 org.apache.catalina.core.StandardContext loadOnStartup
    SEVERE: Servlet /RESTfulExample threw load() exception
    java.lang.ClassNotFoundException: org.springframework.aop.support.AopUtils
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1680)
    at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1526)
    at com.sun.jersey.spi.spring.container.SpringComponentProviderFactory.getInjectableInstance(SpringComponentProviderFactory.java:240)
    at com.sun.jersey.spi.spring.container.SpringComponentProviderFactory.access$100(SpringComponentProviderFactory.java:81)
    at com.sun.jersey.spi.spring.container.SpringComponentProviderFactory$SpringManagedComponentProvider.getInjectableInstance(SpringComponentProviderFactory.java:230)
    at com.sun.jersey.server.impl.component.IoCResourceFactory$SingletonWrapper.init(IoCResourceFactory.java:179)
    at com.sun.jersey.server.impl.application.WebApplicationImpl$10.f(WebApplicationImpl.java:584)
    at com.sun.jersey.server.impl.application.WebApplicationImpl$10.f(WebApplicationImpl.java:581)
    at com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:193)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.getResourceComponentProvider(WebApplicationImpl.java:581)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.initiateResource(WebApplicationImpl.java:658)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.initiateResource(WebApplicationImpl.java:653)
    at com.sun.jersey.server.impl.application.RootResourceUriRules.(RootResourceUriRules.java:124)
    at com.sun.jersey.server.impl.application.WebApplicationImpl._initiate(WebApplicationImpl.java:1298)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.access$700(WebApplicationImpl.java:169)
    at com.sun.jersey.server.impl.application.WebApplicationImpl$13.f(WebApplicationImpl.java:775)
    at com.sun.jersey.server.impl.application.WebApplicationImpl$13.f(WebApplicationImpl.java:771)
    at com.sun.jersey.spi.inject.Errors.processWithErrors(Errors.java:193)
    at com.sun.jersey.server.impl.application.WebApplicationImpl.initiate(WebApplicationImpl.java:771)
    at com.sun.jersey.spi.spring.container.servlet.SpringServlet.initiate(SpringServlet.java:117)
    at com.sun.jersey.spi.container.servlet.ServletContainer$InternalWebComponent.initiate(ServletContainer.java:318)
    at com.sun.jersey.spi.container.servlet.WebComponent.load(WebComponent.java:609)
    at com.sun.jersey.spi.container.servlet.WebComponent.init(WebComponent.java:210)
    at com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:373)
    at com.sun.jersey.spi.container.servlet.ServletContainer.init(ServletContainer.java:556)
    at javax.servlet.GenericServlet.init(GenericServlet.java:212)
    at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1206)
    at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1026)
    at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4421)
    at org.apache.catalina.core.StandardContext.start(StandardContext.java:4734)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
    at org.apache.catalina.core.StandardHost.start(StandardHost.java:840)
    at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
    at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463)
    at org.apache.catalina.core.StandardService.start(StandardService.java:525)
    at org.apache.catalina.core.StandardServer.start(StandardServer.java:754)
    at org.apache.catalina.startup.Catalina.start(Catalina.java:595)
    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.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
    at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
    19.Oca.2012 02:00:24 org.apache.coyote.http11.Http11Protocol start
    INFO: Starting Coyote HTTP/1.1 on http-8080
    19.Oca.2012 02:00:24 org.apache.jk.common.ChannelSocket init
    INFO: JK: ajp13 listening on /0.0.0.0:8009
    19.Oca.2012 02:00:24 org.apache.jk.server.JkMain start
    INFO: Jk running ID=0 time=0/18 config=null
    19.Oca.2012 02:00:24 org.apache.catalina.startup.Catalina start
    INFO: Server startup in 1529 ms

    • Amanda

      Did anyone resolve this issue? I am getting the AOP related error as well.

  • ninja

    It turned out to be simple.

    package com.ninja.jump.service;
    import javax.ws.rs.ext.ContextResolver;
    import javax.ws.rs.ext.Provider;
    import javax.xml.bind.JAXBContext;
    @Provider
    public class JsonProvider implements ContextResolver&lt;JAXBContext&gt; {
        @Override
        public JAXBContext getContext(Class&lt;?&gt; type) {
            return null;
        }
    }
  • ninja

    Hi mkyong,
    This is nice article. I am doing the exactly same way. One Challenge I am facing right now is to write a JUnit for a resource class.

    package com.ninja.jump.service;
    import junit.framework.Assert;
    import org.junit.Test;
    import com.sun.jersey.api.client.WebResource;
    import com.sun.jersey.test.framework.JerseyTest;
    import com.sun.jersey.test.framework.spi.container.TestContainerException;
    public class WadlServiceTest extends JerseyTest {
        public WadlServiceTest() throws TestContainerException {
            super(&quot;com.ninja.jump.service&quot;);
        }
        @Test
        public void getWadl_noargs_success() {
            WebResource webResource = resource();
            webResource = webResource.path(&quot;application.wadl&quot;);
            String wadl = webResource.get(String.class);
            Assert.assertNotNull(wadl);      
        }
    }

    Above code works just fine. But, as soon as I test any resource that has
    @Autowired variable, it fails.

    This is because I cannot extend my JUnit to both AbstractJUnit4SpringContextTests and
    JerseyTest at the same time.

    After hours of googling, I came across to the following article. But, their spring version and jersey version is bit old and I am getting many version conflicts.

    http://geek.riffpie.com/unit-testing-restful-jersey-services-glued-together-with-spring/

    After I saw this article, version number matches with mine and wondering if you have faced the same issue and importantly you already solve this issue.

    Looking forward your reply.

  • Kit

    In my previous comment, I forgot to mention that my existing project using your sample code could be compiled without any errors. However, when I start Tomcat, I got the error. I have added 4 more lines before the error so that you have a better idea what went wrong:

    22-Jul-2011 4:47:59 PM com.sun.jersey.api.core.PackagesResourceConfig init
    INFO: Scanning for root resource and provider classes in the packages:
      com.mycompany.web.services.rest
    22-Jul-2011 4:47:59 PM org.apache.catalina.core.ApplicationContext log
    SEVERE: StandardWrapper.Throwable
    java.lang.NoSuchMethodError: org.objectweb.asm.ClassReader.accept(Lorg/objectweb/asm/ClassVisitor;I)V
    	at com.sun.jersey.spi.scanning.AnnotationScannerListener.onProcess(AnnotationScannerListener.java:133)
    	at com.sun.jersey.core.spi.scanning.uri.FileSchemeScanner$1.f(FileSchemeScanner.java:86)
    	at com.sun.jersey.core.util.Closing.f(Closing.java:71)

    Thank you.

    • http://www.mkyong.com mkyong

      I support that’s your last caused by, from the error message, it showed that asm.jar has no this method, this is caused by the wrong version of asm is included.

      To fix it, try upgrade asm.jar to latest version, or try other versions one by one to match your case.

      • Kit

        Thank you for your help. Everything works fine now.

        • newbie

          Hello,

          I’m running into the same issue described above. I have tried multiple versions of the asm.jar library but haven’t had any luck yet. Can you post the version you are using for your asm.jar.

          • http://www.mkyong.com mkyong

            This is one of the core reason of using Maven, to get rid of jar too many version concern.

            Download attached example, build with Maven, then it will grab all necessary dependencies, including the asm.jar automatically. Then you will know which asm.jar should use.

  • Kit

    Hi Mkyong,

    Thank you for your article. I have downloaded your zip file and then imported it to Eclipse. Unfortunately, I get the following errors:

    Project ‘RESTfulExample’ is missing required library: ‘/home/username/.m2/repository/commons-logging/commons-logging/1.1.1/commons-logging-1.1.1.jar’
    Project ‘RESTfulExample’ is missing required library: ‘/home/username/.m2/repository/org/springframework/spring-aop/2.5.6.SEC02/spring-aop-2.5.6.SEC02.jar’
    Project ‘RESTfulExample’ is missing required library: ‘/home/username/.m2/repository/org/springframework/spring-beans/3.0.5.RELEASE/spring-beans-3.0.5.RELEASE.jar’
    Project ‘RESTfulExample’ is missing required library: ‘/home/username/.m2/repository/org/springframework/spring-expression/3.0.5.RELEASE/spring-expression-3.0.5.RELEASE.jar’
    The project cannot be built until build path errors are resolved

    I am pretty new to Jersey and Spring, and would like to use them together in a project. Would you please help me to fix them? Thank you and I appreciate your help.

    Kit

    • http://www.mkyong.com mkyong

      This is Maven project, please build with Maven, it will download all the project dependencies.

      Install Maven, in command prompt, type “mvn eclipse:eclipse -Dwtpversion=2.0″