删除 guice servlet 后,我需要进行一些清理。使用 guice servlet 时是否可以挂钩到 servlet 破坏?我需要使用喷油器进行清理工作。
我可以覆盖 中的contextDestroyed
方法GuiceServletContextListener
,但是如何访问注入器?
有没有更好的方法来应对 servlet 破坏?
删除 guice servlet 后,我需要进行一些清理。使用 guice servlet 时是否可以挂钩到 servlet 破坏?我需要使用喷油器进行清理工作。
我可以覆盖 中的contextDestroyed
方法GuiceServletContextListener
,但是如何访问注入器?
有没有更好的方法来应对 servlet 破坏?
我可以覆盖 GuiceServletContextListener 中的 contextDestroyed 方法,但是如何访问注入器?
你可以这样做:
public class MyGuiceServletConfig extends GuiceServletContextListener {
private final Injector injector = Guice.createInjector(new ServletModule());
@Override
protected Injector getInjector() {
return injector;
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
injector.getInstance(MyCleanUp.class);
}
}
或者像这样:
public class MyGuiceServletConfig extends GuiceServletContextListener {
@Override
protected Injector getInjector() {
return Guice.createInjector(new ServletModule());
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
Injector injector = (Injector) sce.getServletContext()
.getAttribute(Injector.class.getName());
}
}