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.
This is the project structure that you’ll have to setup after the tutorial.
src |--main | +--java | +--... | +--resources | +--webapp | +--WEB-INF | |--beans.xml | |--web.xml | +--META-INF | |--context.xml pom.xml
Install and Configure CDI in Tomcat (Weld implementation)
Add weld-servlet.jar in your project webapp’s WEB-INF/lib.
Or add the following dependency to maven to be automatically included in the war file.
<dependency> <groupId>org.jboss.weld.servlet</groupId> <artifactId>weld-servlet</artifactId> <version>2.2.14.Final</version> </dependency>
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:
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"?> <Context> <Resource name="BeanManager" auth="Container" type="javax.enterprise.inject.spi.BeanManager" factory="org.jboss.weld.resources.ManagerObjectFactory" /> </Context>
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.
- 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.