Java Reference
In-Depth Information
Our solution was to hard‐wire the resources. Even though this gave us an “uglier”
app, the app started up in lightning speed, solving our performance issue.
The moral of this story is not that DI is a bad pattern to implement on mobile
devices but that a poor implementation of DI (whether on a mobile device or not) in
the wrong context can cause huge problems.
IMPLEMENTING DI IN JAVA EE
J2EE did not offer DI out of the box until Java EE 5. Instead, in J2EE, beans and resources were
accessed using Java Naming and Directory Interface (JNDI) context lookups. This approach caused
hard‐wiring and relied on a heavyweight server‐based container, which made testing almost harder
than writing the actual code.
With the release of Java EE 5 and EJB 3, DI became an integral part of the Enterprise Java platform.
To get rid of XML‐based coni guration, several annotations were introduced to perform injection:
@Resource (JSR250) is for injecting data sources, Java Message Service (JMS), URL, mail,
and environment variables.
@EJB (JSR220) is for injecting EJB.
@WebServiceRef is for injecting web services.
With the release of Java EE 6, CDI, and EJB 3.1, DI became a much more capable, and thus more
interesting, topic in Java EE.
In EJB 3.1, an interface was no longer mandatory for EJBs. Also, a new EJB web proi le was
introduced that offers a simplii ed lighter EJB container. A new and improved injection annotation
@Inject was introduced (JSR229 and JSR330), which also provided a common interface for
injection between other DI frameworks in the Java realm.
The @Inject annotation DI is type safe because it injects a dependency based on the type of the
object reference. If you were to refactor the code in Listing 5‐1, you would remove the constructor
and add an @Inject annotation to the UserDataRepository i eld. The code would look something
like Listing 5‐7.
LISTING 5‐7: The refactored UserService class using @Inject
package com.devchronicale.di;
import javax.inject.Inject;
class UserService {
@Inject
continues
 
Search WWH ::




Custom Search