users@jersey.java.net

[Jersey] Re: Registering Injected ExceptionMapper Instances via SpringServlet

From: James Shaw <js102_at_zepler.net>
Date: Fri, 21 Dec 2012 16:54:04 +0000

On 29 November 2012 18:02, Gregory Wright <daecabhir_at_gmail.com> wrote:
> Jersey: 1.12
> Spring: 3.11
> JDK: 1.6.0_35
> Tomcat: 6..0.33
>
> I am trying to register ExceptionMapper<T> instances for a Jersey servlet
> that are instantiated by a Spring IoC container in the context of a
> SpringServlet, and am running into ye olde "The scope of the component class
> X must be a singleton" exception during the Jersey servlet initialization.
> I'm not in a position to post the actual code at this time, so I'm going to
> give the essentials of the implementation to see if something obvious jumps
> out at someone, or if I can be pointed at some documentation that I have
> missed.
>
>
> The ExceptionMapper<T> instance is essentially as follows:
>
>
> // ... package definitions omitted ...
>
> @Provider
> @Singleton
> public class MyExceptionMapper
> implements ExceptionMapper<MyException>
> {
> // ... injected attributes omitted ...
>
> @Override
> public Response toResponse(MyException exception)
> {
> // ... specific handling logic omitted ...
>
> return
> Response.status(Status.BAD_REQUEST).entity(exception.getMessage()).build();
> }
> }
>
>
> The bean definition in applicationContext.xml is as follows, which defaults
> to singleton scope (and adding an explicit scope specifier doesn't seem to
> change the behavior):
>
> <bean id="myExceptionMapper" class="my.package.MyExceptionMapper" />
>
>
> The Spring context loader listener and SpringServlet configuration in
> web.xml are essentially boilerplate, and the servlet will load, initialize
> and operate properly with other inject attributes when the bean definition
> for MyExceptionMapper is commented out of the applicationContext.xml. But
> when the bean definition is present in applicationContext.xml, I get log
> messages to the effect of:
>
>
> SpringProviderFactory - Registering Spring bean, myExpectionMapper, of type
> my.package.MyExceptionMapper as a provider class
> SpringProviderFactory - Registering Spring bean, myServiceController, of
> type my.package.MyServiceController as a root resource class
> ... other root resource classes loading ...
> SpringServlet - Exception occurred when initialization
> java.lang.RuntimeException: The scope of the component class
> my.package.MyExceptionMapper must be a singleton
> at som.sun.jersey.core.spi.component.ioc.IoCProviderFactory.wrap(...)
>
>
> I have tried placing MyExceptionMapper in the scanned packages hierarchy to
> be picked up by the SpringServlet during initialization, and in a separate
> package hierarchy, and the results do not change.
>
I've seen this problem, but we're using Spring Java configuration, not
XML configuration. Have you tried setting the bean's scope to
singleton explicitly? That's worked for me before.