RESTful web services are all the rage these days and Java’s no exception. The most mature among the RESTful frameworks in Java, is the Restlet Framework. In fact, the Restlet developers, had a lot of input on the JAX-RS spec and therefore support the standard really well.
However, one of the issues I had when starting with Restlets (using JAX-RS), was getting them to work with Spring. Restlets alone work well with Spring, but using the JAX-RS extension was slightly more challenging, as you have to create your own method of injecting objects into the framework.
Here is a sample application class:
Note: I added the import statements so it would be clear I’m using the JAX-RS extension for Restlets
This is all fine and good. This is what you would do if you were just creating a regular JAX-RS application using Restlets. However, it’s not so simple if you want to use Spring beans. Notice, I’m adding the class I want to bind as my resource via its static classname. Generally, you can’t reference Spring beans this way without accessing the internals and that’s what we’ll have to do here.
The way to do this is by overriding the Restlet ServerServlet with your own SpringServerServlet class:
The JAX-RS extension allows you to set an object factory, and in this case we’re overriding the object factory to use Spring’s AutowireCapableBeanFactory. This way, we can specify the static classname and get a valid Spring bean in return.
One last thing to add is that you’ll have to use this SpringServerServlet in your web.xml instead of the standard ServerServlet.
Hopefully that saves you some time!
Hello, I'm Arthur. I'm a software engineer.
Currently my focus is on test-driven software design and
development for scalable web services and web applications.
This site is largely dedicated, but not limited to, topics in this area.
Feel free to contact me using any of the links below.