Add Spring Dependency Injection Support to a JAX-RS Jersey App

To make our Jersey RESTful Web Service Application be able to @Autowire service classes and inject Java Beans we will need to add to it a support for Spring Dependency Injection(DI) and below I am going to share with you how to do it.

JAX-RS, Jersey and Spring DI Dependencies in POM.XML

Once we have created our very basic Jersey JAX-RS application and have added the jaxrs-ri and the jersey-media-moxy dependencies to our pom.xml file there are a couple of more dependencies that we need to add to pom.xml file for our Spring DI to work. These two dependencies are: jersey-spring3 and commons-logging.

So the complete pom.xml file that I have now in my project and which is working well is with the two new dependencies already added is below:

Extending ResourceConfig to Support Spring Dependency Injection

To make our web app to function like a Jersey application we needed to create a custom class which extends javax.ws.rs.core.Application. But now, to support Spring DI, instead of making our class extend Application class, we will need to extend ResourceConfig class. So the complete custom class which serves for me as Jersey Application Starting point looks like this:

Create applicationContext.xml File

List Java Beans and service classes you want to be able to @Autowire into your application in applicationContext.xml file which in my case I have created in src/main/resources folder. I am going to @Autowire only one service class and below is my complete applicationContext.xml file:

Building RESTful Web Services is much more fun when you know the subject very well. Check out the video courses below which will definitely help you on your way to becoming a very good RESTFul Web Services developer.

Java Web Services. Video Course.

Learn how to design,create , consume and secure SOAP and REST web services from scratch in easy steps.