user959135
user959135

Reputation: 31

Guice Servlet with Embedded Tomcat

I am trying to introduce Guice(v3.0) in my project. I am using embedded tomcat(v7.0.34) and Jersey(v1.18) to host rest services.

Before introducing any Guice dependency injection I had the following configuration

//Main Class
Context context = tomcat.addWebapp("/", new File(webappDirLocation).getAbsolutePath());
    tomcat.addServlet(context, "Jersey REST Service", new ServletContainer(new DefaultResourceConfig(EntityResource.class)));
    context.addServletMapping( "/rest/*", "Jersey REST Service");
    tomcat.start();
    tomcat.getServer().await();


//EntityResource
@Path("entity")
public class EntityResource {    
final EntityService entityService;
public EntityResource()
{
    this.entityService = new EntityService();
}

@Path("")
@Produces("application/json")
@GET
public Entity getEntity(){
    return entityService.getEntity();
}

This worked fine. I was able to do GET on /rest/entity.

After adding Guice's constructor injection to EntityResource it looks like this

final EntityService entityService;
@Inject
public EntityResource(EntityService entityService)
{
    this.entityService = entityService;
}

@Path("")
@Produces("application/json")
@GET
public Entity getEntity() {
    return entityService.getEntity();
}

This gives an error "Missing dependency for constructor public com.my.rest.EntityResource(com.my.service.EntityService) at parameter index 0". I am guessing this is because of Guice's constructor injection.

Upvotes: 0

Views: 1000

Answers (1)

user959135
user959135

Reputation: 31

Adding servlet in web.xml made it work

//web.xml
<web-app>
<filter>
<filter-name>guiceFilter</filter-name>
<filter-class>com.google.inject.servlet.GuiceFilter</filter-class>
</filter>

<filter-mapping>
<filter-name>guiceFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<listener>
<listener-class>com.my.servlet.MyServletListener</listener-class>
</listener>

//MyServletListener
public class MyServletListener extends GuiceServletContextListener {
@Override
public Injector getInjector() {
    return Guice.createInjector(new JerseyServletModule(){
        @Override
        protected void configureServlets() {
            bind(EntityResource.class);
                bind(EntityService.class).to(com.my.impl.EntityService.class).in(Singleton.class);
            serve("/rest/*").with(GuiceContainer.class);
        }
    });
}
}

Still looking for how to do this without web.xml.

Upvotes: 2

Related Questions