Skip to content

Instantly share code, notes, and snippets.

@stickfigure
Created April 26, 2015 17:51
Show Gist options
  • Save stickfigure/5ff4b814b8a08e4e1f57 to your computer and use it in GitHub Desktop.
Save stickfigure/5ff4b814b8a08e4e1f57 to your computer and use it in GitHub Desktop.
A better way to integrate Guice and Resteasy
package com.example;
import com.google.inject.Injector;
import org.jboss.resteasy.plugins.guice.ModuleProcessor;
import org.jboss.resteasy.plugins.server.servlet.FilterDispatcher;
import org.jboss.resteasy.spi.Registry;
import org.jboss.resteasy.spi.ResteasyProviderFactory;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
/**
* Use this instead of the Resteasy FilterDispatcher and it will be properly integrated with Guice.
* The normal Resteasy Guice integration via servlet context listener is not the "guice way".
*
* Note that you must map this filter in Guice so that it gets proper injection.
*
* @author Jeff Schnitzer
*/
@Singleton
public class GuiceResteasyFilterDispatcher extends FilterDispatcher
{
private Injector injector;
@Inject
public GuiceResteasyFilterDispatcher(Injector injector) {
this.injector = injector;
}
/**
* Also initializes all Guice bindings for
*/
@Override
public void init(FilterConfig cfg) throws ServletException {
super.init(cfg);
final ServletContext context = cfg.getServletContext();
final Registry registry = (Registry) context.getAttribute(Registry.class.getName());
final ResteasyProviderFactory providerFactory = (ResteasyProviderFactory) context.getAttribute(ResteasyProviderFactory.class.getName());
final ModuleProcessor processor = new ModuleProcessor(registry, providerFactory);
processor.processInjector(injector);
}
}
@natros
Copy link

natros commented Mar 2, 2016

Is there a reason to not to use the getDispatcher()?

Registry registry = getDispatcher().getRegistry();
ResteasyProviderFactory providerFactory = getDispatcher().getProviderFactory();

@weisebrazil
Copy link

Now, we need to pass a init parameter to work right.

bind(GuiceResteasyFilterDispatcher.class);
filter("/*").through(GuiceResteasyFilterDispatcher.class, values(new String[]{"resteasy.servlet.context.deployment","true"}));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment