users@jersey.java.net

Dependency resolution for container request and response filters

From: Brian Gilstrap <brian_at_gilstraps.net>
Date: Wed, 13 Jan 2010 15:31:56 -0600

I currently start my standalone Grizzly-based service using the Spring integration (1.0.2) like this:

public class Main3c {

    private static final int PORT = 3131;
    public static final String PACKAGES = Main.class.getPackage().getName();

    public static void main(String[] args) throws IOException {
        Map<String, String> initParams = new HashMap<String, String>();
        initParams.put(ResourceConfig.PROPERTY_CONTAINER_REQUEST_FILTERS, CachingContainerRequestFilter.class.getName());
        initParams.put(ResourceConfig.PROPERTY_CONTAINER_RESPONSE_FILTERS, CachingContainerResponseFilter.class.getName());
        initParams.put("com.sun.jersey.config.property.packages", PACKAGES);
        ExceptionMappersInit.factory = new ClassPathXmlApplicationContext("Stage3.xml");
        ExceptionMappersInit.populateExceptionMappers();
        GrizzlyWebContainerFactory.create("http://localhost:" + PORT + "/", StandaloneSpringServlet.class, initParams);
        System.out.println("Music service now running...");
    }

}

My filters are currently just stubs, like this:

public class CachingContainerResponseFilter implements ContainerResponseFilter {
    public ContainerResponse filter(final ContainerRequest request, final ContainerResponse response) {
        System.err.println("We were called to filter a response!");
        return response;
    }
}

The startup strategy above is great for getting my request and response filter instances instantiated and registered. However, those filters need access to some infrastructure objects. What is a good way to make them available?

The filter objects themselves don't take any arguments in their constructors, so I don't think I can use IOC dependency injection (being proven wrong here would be great! :-) ). I wondered if there is some sort of @Provider and @Context annotation approach I could use. I'd be happy to could provide additional init params that would do the trick somehow. Or I'd be happy to provide a reference to some class that Jersey would instantiate during initialization which could then have enough context to create my filters and register them with Jersey (along with creating the infrastructure objects needed and making my filters aware of those other objects).

What I really don't want to have to do is use a singleton. What can I do to avoid a singleton?

Thanks,
Brian