Java Reference
In-Depth Information
12.2. CDI beans
Unlike EJB, CDI doesn't have its own component model. A bean within CDI can be a man-
aged bean (JSF), Enterprise Java Bean, or POJO. All of these types of objects can use the
full range of services provided by CDI. In this chapter, when we refer to a CDI bean we
usually mean a POJO unless stated otherwise. CDI beans are thus very flexible and not a
distinct class of beans like JSF-managed beans or EJBs.
Although CDI is in no way tied to JSF, CDI beans (POJOs) should be used instead of JSF-
managed beans. This means that you should no longer be defining beans with faces-con-
fig.xml or using the @ManagedBean annotation.
A CDI bean is associated with a context, has a type, and may be qualified. The context de-
termines the lifecycle of the bean, whether it lives for only one request or it's a part of a
conversation or workflow. One of the features of CDI is the fact that DI uses the type sys-
tem. As a result, whereas other object containers use a string name, CDI uses the Java type
as the name of the bean. Because a bean can only have one type, CDI includes something
call a qualifier, which is type-safe, to distinguish between different instances of the same
type. With this basic understanding of what constitutes a CDI bean, let's look at how you
can use CDI beans.
12.2.1. How to use CDI beans
The creators of CDI took the approach of convention over configuration. This means that
you can start using it immediately. If your application container supports CDI, which it
does if it's at least compliant with Java EE 6, then all you have to do is place a beans.xml
file in your application. The beans.xml file serves two purposes: it's a configuration file
for CDI and it's a marker file so that CDI knows whether it needs to scan the JAR file for
beans. The following listing shows an empty configuration file. This file should be placed
in the META-INF directory of any archive containing the beans.
Listing 12.1. Empty beans.xml configuration file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
Search WWH ::

Custom Search