Java Reference
In-Depth Information
this to be done, the current conversation must be acquired via injection and the begin
method invoked. A conversation can then either be programmatically terminated or expire
after a fixed time period. The timeout is thus less than that of a session.
We'll revisit conversations later in this chapter once we've covered the basics of CDI. Con-
versations are one of the more advanced features. Conversations are an example of how the
EE standard grows because of the experimentation of proprietary technologies. Conversa-
tions were first introduced by JBoss Seam and then later integrated into Java EE 6 and later.
12.3. Next generation of dependency injection
Dependency injection has been around for many years. It was popularized by proprietary
frameworks. CDI looks to these frameworks for inspiration and takes it one step further
by providing type-safe dependency injection. CDI doesn't use freeform strings to resolve
dependencies but instead uses the Java type system. It couples this with component life-
cycles and component scoping to provide the next logical step for dependency injection.
Let's start off by looking at the @Inject annotation that you'll use extensively.
12.3.1. Injection with @Inject
The @Inject annotation is the heart of CDI. This annotation marks a point where an in-
stance of a bean needs to be injected. It can be placed either on an instance variable or on
a constructor. When the CDI container goes to instantiate a class containing fields marked
with @Inject , it checks to see if an instance already exists; if not, it creates a new in-
stance and sets the value. It's important to note that if a bean isn't annotated with a scop-
ing annotation ( @Conversation , @RequestScoped , or @SessionScoped , among
others) then it falls under the dependent scope, which can be explicitly marked using the
@Dependent annotation. CDI looks at the type on the injection point, as well as any qual-
ifier annotations, to figure out what object needs to be injected or created and then injected.
All of this resolution is performed when a bean is first instantiated.
Let's look at an example of using the @Inject annotation in ActionBazaar. Within Ac-
tionBazaar, the LandingController bean backs the homepage. It's an application-
scoped bean that caches the newest items to be featured on the homepage. The newest items
are cached because it doesn't make sense to hit the database for each page request. Retriev-
Search WWH ::




Custom Search