users@jersey.java.net

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

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

Frederic,

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

@Component
@Path("/resource")
public class MyResource {

  @InjectParam
  private MySpringBean bean;

  @GET
  public Response doGet() {
    bean.getSomething()
    // ...
  }
}

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

    <!-- Enable annotation configuration -->
    <context:annotation-config/>

    <context:component-scan base-package="com.company.rest.resources"/>

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

Tauren



On Tue, Apr 5, 2011 at 2:02 AM, Frederic Bergeron
<FBergeron_at_rocketmail.com>wrote:

> 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
>