Inject ServletContext in Abstract Module

835 views
Skip to first unread message

Gambo

unread,
Oct 20, 2011, 11:21:14 AM10/20/11
to google-guice
Hi there,

I want to inject the servletContext within my module to bind the
realpath param to a named object:

public class ServiceModule extends AbstractModule {

protected void configure() {

bind(String.class).annotatedWith(Names.named("realPath")).toInstance(servletContext.getRealPath("/
temp"));

}

}

Before I injected the servletcontext into one of my services but Guice
is throwing now a lot of warnings which say that this is not a good
idea.

How can I achieve this?

Thanks

Mihai Roman

unread,
Oct 21, 2011, 5:41:56 AM10/21/11
to google-guice
Hi,

Get the path when the context initializes in the event listener and
send it up to the ServletModule. You can then use it in other
AbstractModules you are implementing and installing in your
ServletModule.

I hope this helps:

public class MyServletConfig extends GuiceServletContextListener {
private String path;

@Override
public void contextInitialized(ServletContextEvent
servletContextEvent) {
this.path =
servletContextEvent.getServletContext().getRealPath("/");
}
@Override
protected Injector getInjector() {
return Guice.createInjector(new MyServletModule(path));
}
}

~Mihai

Filipe Sousa

unread,
Oct 21, 2011, 7:20:25 AM10/21/11
to google...@googlegroups.com
I think you need to call super.contextInitialized(servletContextEvent) otherwise getInjector() won't be called

Mihai Roman

unread,
Oct 21, 2011, 8:31:41 AM10/21/11
to google-guice
Yes, you certainly need to call the super:

@Override
public void contextInitialized(ServletContextEvent
servletContextEvent) {
this.path =
servletContextEvent.getServletContext().getRealPath("/");
super.contextInitialized(servletContextEvent);
}

My original code had other initializations and logging, I've deleted
it by mistake when I posted the snippet. Thanks!
Reply all
Reply to author
Forward
0 new messages