Java EE CDI beans deployed in external library (WEB-INF/lib JAR file)
One of the objectives of the beans.xml file in a CDI application is to notify the container where to search for CDI managed beans. In this short tutorial we will see how to configure a JAR file - containing CDI beans - to be scanned by the container inside a web application (WEB-INF/lib folder).
This tutorial considers the following environment:
- Ubuntu 12.04
- JDK 184.108.40.206
- Weld 1.1.10
- Tomcat 7.0.35
Weld is the CDI reference implementation
The JAR file
We have already seen in another tutorial that we need a beans.xml file inside the WEB-INF folder of a web application to notify the container to scan the application classes folder for CDI beans (see Configuring CDI with Tomcat example).
In order to deploy CDI beans in a JAR file inside the WEB-INF/lib web application folder we must instruct the container to also scan the JAR for those CDI beans.
In this case the beans.xml file goes into the JAR META-INF folder.
The test application
We will use a very simple web application to test this scenario. The application consists in a multiple module Maven project: A war and the lib that will contain the CDI beans. If you don't know how to configure a multiple module Maven project please see How to create a multiple module project using Maven.
Following next is the application structure:
As we can see we have the beans.xml file inside the META-INF lib project folder. When we build the war project the lib project will be included in the WEB-INF/lib as a JAR file. Since the JAR file contains the beans.xml file the container will know that the JAR must be scanned for CDI beans.
The CDI bean which interface is Service and is also contained in the lib project will be injected in TestServlet web application servlet.
Bad configuration symptoms
If we don't correctly deploy our JAR containing the CDI beans we usually get a CDI initialization exception stating that the required dependencies were not found, ie. the container could not find any dependencies that satisfy the injection point conditions:
The testing application is available for download at the end of this page and was tested with Tomcat.