Kohei Nozaki's blog 

Lean example of Tomcat 8 + Guice 4

Posted on Monday Aug 03, 2015 at 06:56PM in Technology

I prefer Java EE stack usually, but I need to learn a Tomcat based stack for some reasons these days. in this entry, I introduce you a very simple example of Tomcat 8 + Guice 4 app which uses GuiceFilter and GuiceServletContextListener so that bring Guice to a Servlet based web application.

The entire project which based on Maven can be obtained from My GitHub repository.




<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"






We need to declare servlet mappings and the mappings between interfaces and implementations here.

public class MyGuiceServletConfig extends GuiceServletContextListener {
    protected Injector getInjector() {
        return Guice.createInjector(new ServletModule() {
            protected void configureServlets() {

Service class

We use a pair of a very simple implementation of a service class. it simply creates a greetings which uses an argument.


public interface MyService {
    String hello(String name);


public class MyServiceImpl implements MyService {
    public String hello(String name) {
        return "Hello, " + name;


Note that we use @javax.inject.Singleton and @javax.inject.Inject annotations, that are standardized JSR API.

public class MyServlet extends HttpServlet {

    private MyService myService;

    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

Test run

After deployment, send a request to check the response:

$ curl http://localhost:8080
Hello, Guice

Other things/functions need to be studied

  • Transaction management

  • CDI Producer equivalent

  • AOP

  • Automatic implementation scanning/binding

No one has commented yet.

Leave a Comment

HTML Syntax: NOT allowed