Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Jersey 2 with Spring IoC container

Tags:

spring

jersey

What is the best way to enable injection of spring beans into Jersey 2? Jersey seems to not support this natively.

What is needed to wire the 2 frameworks together? In pom.xml and web.xml?

like image 533
user1829836 Avatar asked Jan 31 '13 13:01

user1829836


1 Answers

Jersey 2.3 has now spring support:

https://jersey.github.io/documentation/latest/user-guide.html#spring

As stated in the documentation

The Spring extension module configuration is based on annotations

So you have to tell spring to scan your classpath, for example:

<context:component-scan base-package="my.package.to.resources">

and annotate your resource class with a spring annotation (I advise to use @Component, and then specify the jersey resource scopes @Singleton/@PerLookup/@RequestScoped )

@Component
@Singleton
@Path("example")
public class Example {

    //Spring beans can't be injected directly into JAX-RS classes by using Spring XML configuration
    @Autowired
    private MyOtherBean myOtherBean;

    @GET @Path("hello")
    public String hello() {
        return myOtherBean.hello();
    }
}
like image 62
Fabio Bonfante Avatar answered Sep 28 '22 16:09

Fabio Bonfante