Java Reference
In-Depth Information
for succinct code examples, it illustrates some of the best practices for integrating the two
technologies. CDI is used in lieu of JSF-backing beans and support, the JSF interface. Note
that CDI isn't tied to JSF—CDI is agnostic to the web framework. CDI beans keep the
business layer clean by isolating UI functionality in a distinct layer. This is also good to
do with both SOAP and RESTful web services—an EJB shouldn't be coded to support a
SOAP-based web service or return JSON data for a RESTful service. A good architecture
for your application, which isolates responsibility into separate layers, is made easier with
CDI because CDI makes the integration between layers seamless.
Because EJBs are also CDI beans, one very important practice is to use @Inject instead
of @EJB . The configurability provided by CDI makes testing an application much easier.
Using the beans.xml configuration file, the instances injected can be changed for the pur-
poses of unit and integration testing. A mock object can be injected so that a layer can
be tested for its resilience to database exceptions or other types of errors that are difficult
to simulate. Furthermore, the @Inject makes it irrelevant whether a bean is an EJB or
simply a POJO—at any point in the future, you can upgrade the bean from a POJO to an
EJB as the application evolves.
The support for decorators in CDI enables a highly tailored form of crosscutting that's
much more powerful than what's available with EJB interceptors. This type of interceptor
enables you to extract logic that's tied to the implementation of business logic but is dis-
tinctly separate. The example of a fraud detector in ActionBazaar is a good example. Al-
though this is definitely related to placing a bid, it's logic that's distinct from the actual
mechanism of registering the bid and will obviously evolve in sophistication. It needs
to be separate—if you go in to implement a new fraud detector, you don't want that
code comingled with the logic that processes the bid. An enhancement in fraud detection
shouldn't destabilize the bid code and require a full QA regression of such a critical func-
tion for a crosscutting concern.
CDI events are extremely powerful and useful for reducing coupling in code—both in
the replacements of JSF-backing beans and EJBs. CDI events should be used to decouple
beans so that each bean doesn't have a reference to every other bean in the system. Highly
coupled systems can be a nightmare where one change has an unintended ripple effect or
requires an inordinate number of code changes. CDI events can thus be used for objects to
fire events without needing to know who is receiving them or the receiver needing to have
a reference for the sender. This dramatically reduces spaghetti code. One caveat, however,
is that this functionality can be abused—events don't cross the JVM boundary. This means
Search WWH ::




Custom Search