Jersey Root Resource member variable initialization

536 Views Asked by At

I've inherited a little web application that contains root resources that are similar to:

import javax.ws.rs.Path;

@Path("somepath")
public class ResourceClass
{
   DataSource source = new SpecificDataSource();
   @GET
   public String getInfo() {
      return source.queryThatReturnsNumber().toString();
   }
}

And there are a few different classes similar to this. Is there a method to set the source member variable to something other than SpecificDataSource? I'm fairly new to this, but in a traditional POJO I would have a constructor that takes a class implementing the DataSource interface and sets source to that object. For Jersey, I don't believe that I have direct control over the construction of these objects.

Simply put, is there a way to provide an initialization mechanism for Jersey Root Resource classes?

2

There are 2 best solutions below

0
On

Since you are using a datasource, I would recommend configuring jndi for your resource. Depending on your server environment there will be different ways to configure your jndi resources. This is a good way to have your Singleton resources configured and or pooled by the application server.

DataSource ds = (DataSource) new InitialContext().lookup("jdbc/specificResource");
con = ds.getConnection();

If you are using an ejb supported application server (GlassFish, Tomee, Jboss) you can also use the native di support.

@Resource(name="specificResource")
DataSource ds;

Here is a nice tutorial on the web. http://penguindreams.org/blog/running-beans-that-use-application-server-datasources-locally/

As a simple alternative for more complex dependencies. I would recommend jersey-guice dependency injection. I have used many times and it is easy to configure and use.

0
On

You might have figured this out; however you can achieve it by using the Jersey filter. I have modified your code to achieve it. This works with Jersey 1.8; for later versions the syntax/names may be different.

@Path("somepath")
public class ResourceClass implements ContainerRequestFilter
{
    private static DataSource source = new SpecificDataSource();
    @GET
    public String getInfo() {
        return source.queryThatReturnsNumber().toString();
    }

    @Override
    public ContainerRequest filter(ContainerRequest requestContext) {
        // initialize DataSource source
        return requestContext;
    }
}