[Jersey] Re: How to access a Spring bean from Jersey resource?

From: Tauren Mills <>
Date: Tue, 5 Apr 2011 03:36:45 -0700


Add an @Component annotation to your resource class and then use
@InjectParam to inject your beans:

public class MyResource {

  private MySpringBean bean;

  public Response doGet() {
    // ...

Your Spring configuration XML will need something like this in it:

    <!-- Enable annotation configuration -->

    <context:component-scan base-package=""/>

I might have missed something, but I think that's it.


On Tue, Apr 5, 2011 at 2:02 AM, Frederic Bergeron

> Hi,
> I'm implementing a REST API on top of a web application using the Spring
> framework. I managed to implement interoperability between Jersey and
> Spring using the following method:
> @GET
> @Produces( MediaType.APPLICATION_XML )
> public List<Item> getItems( @Context HttpServletRequest req ) {
> HttpSession ses = req.getSession( true );
> WebApplicationContext ctxt =
> WebApplicationContextUtils.getWebApplicationContext( ses.getServletContext()
> );
> ItemCatalogImpl itemCatalog = (ItemCatalogImpl)ctxt.getBean(
> "itemCatalog" );
> ...
> }
> My Jersey resource is able to access successfully a bean that has been
> instanciated by Spring. Yeah!
> However now, I would like to implement unit tests for my REST API using
> InMemoryTestContainerFactory. My solution fails when using
> InMemoryTestContainerFactory. I think the InMemoryTestContainerFactory is
> not able to instanciate/simulate the HttpServletRequest and I cannot access
> the servlet context that is required to get the WebApplicationContext.
> Is there another way for my Jersey resource to access a Spring bean in both
> situations (real servlet and InMemoryTestContainerFactory)? I suspect that
> there are many ways to do it but when I google about that, I'm a bit lost.
> I have seen references to @Component, @Inject, @Autowire, and
> SpringServlet. I have also seen that @Inject is deprecated in the 1.6's
> javadoc. Which way is the best? Any good links on this topic?
> Regards,
> Frederic Bergeron