How to Install and Configure CDI in Tomcat

This tutorial shows how to install and configure CDI in tomcat. To start you must know what tomcat is. Tomcat is a JSP/Servlet container. And more importantly what tomcat is not. Tomcat is not a full-blown EE container. This means by default it does not support CDI, messaging, transactions, security, clustering, fail-over, etc.. You must keep this in mind wether or not to choose for a tomcat implementation. But we all know, sometimes we don’t have control over which application server we have to work with. But you are reading this article which means you have stuck ground. So lets see how to install and configure CDI in tomcat.

Project Structure

This is the project structure that you’ll have to setup after the tutorial.

|    +--java
|        +--...
|    +--resources
|    +--webapp
|        +--WEB-INF
|            |--beans.xml
|            |--web.xml
|        +--META-INF
|            |--context.xml

Install and Configure CDI in Tomcat (Weld implementation)

    1. To start we need a reference implementation of Context and Dependency Injection (CDI). The latest specification out now is CDI 1.2 (JSF-356). We have chosen to use Jboss Weld because the support of tomcat. To add the weld implementation to your project you can do one of the following:

    2. Add weld-servlet.jar in your project webapp’s WEB-INF/lib.

    3. Or add the following dependency to maven to be automatically included in the war file.

  1. Tomcat has a read-only JNDI, so Weld can not automatically bind the BeanManager extension SPI. To bind the beanManger into JNDI, you shouldd create /META-INF/context.xml file in webapp’s web folder. The META-INF directory needs to be on the same level as the WEB-INF directory with the following content.

    <?xml version="1.0" encoding="UTF-8"?>
        <Resource name="BeanManager"
                  factory="org.jboss.weld.resources.ManagerObjectFactory" />

    This will register Weld’s BeanManager factory in Tomcat’s JNDI. This cannot be performed programmatically by Weld because Tomcat’s JNDI is strictly read-only.

  2. If using CDI (Context and Dependency Injection) the deployment descriptor is called beans.xml and is mandatory. It is essential to enable CDI. Make sure the beans.xml is included in the WEB-INF directory.


You may also like...