Skip to content

Tutorial: Configuring Jersey environments without Spring

Corby Page edited this page Jul 14, 2013 · 1 revision

Yoga implements its JAX-RS support with a set of classes that implements MessageBodyWriter. These classes are:

  • JsonSelectorMessageBodyWriter
  • XmlSelectorMessageBodyWriter
  • XhtmlSelectorMessageBodyWriter
  • SelectorBuilderMessageBodyWriter

If you are not using a dependency-injection framework like Spring, then you will need to configure the MessageBodyWriters directly by creating your own subclass.

Example

Let's say that you would like to use Yoga on .JSON requests to your web application. You will create your own subclass of JsonSelectorMessageBodyWriter:

package com.mycompany.yoga

public class MyMessageBodyWriter extends JsonSelectorMessageBodyWriter
{
    public MyMessageBodyWriter() 
    {
        _renderingListenerRegistry = new RenderingListenerRegistry();
        _selector = new CoreSelector();
        _selectorParser = new GDataSelectorParser();
        _classFinderStrategy = new DefaultClassFinderStrategy();
    }
}

Here, we use the constructor to configure the settings that would otherwise be defined in the Spring configuration.

Note that if you don't want Yoga to handle all JSON requests in your application, you can override the isWriteable() method in your MessageBodyWriter implementation to designate which requests should be handled by Yoga.

Now, we update the web.xml configuration for our servlet to make sure that Jersey picks up and applies our new MessageBodyWriter:

<servlet>
    <servlet-name>JerseyServlet</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>com.sun.jersey.config.property.packages</param-name>
        <param-value>com.mycompany.yoga</param-value>
    </init-param>
</servlet>

Adding the com.mycompany.yoga package to the config property ensures that Jersey will use our MessageBodyWriter.