Java Reference
In-Depth Information
CONTEXT AND DEPENDENCY INJECTION
Dependency injection is a design pattern (see Chapter 5, “Dependency Injection and CDI”) that
decouples the relationship between a component and its dependencies. It does this by injecting the
dependency into an object rather than the object creating the dependency by using the new keyword.
w
By removing the creation of the dependency from the object and delegating that responsibility to the
container, you can swap out the dependency for another compatible object at compile time and run time.
Beans that the container manages are called Context and Dependency Injection (CDI)‐managed beans
and are instantiated when the container starts up. All POJOs that have a default constructor and are not
created using the new keyword are CDI beans that are injected into an object based on type matching.
w
To be i njected, the receiving object must declare a i eld, constructor, or method using the @Inject
annotation. Then the type of the declared object is used to determine which dependency to inject.
In Listing 2‐2, you have a POJO that has a default constructor and therefore will be managed as
a CDI bean, and in Listing 2‐3, you inject the managed bean. The container knows to inject the
Message bean based on its type. The container manages only one CDI bean of type Message , so this
is the bean it injects.
LISTING 2‐2: Dependency injection example—Dependency
package com.devchronicles.basicsofjavaee;
public class Message {
public String getMessage(){
return "Hello World!!";
}
}
LISTING 2‐3: Dependency injection example—Receiver
package com.devchronicles.basicsofjavaee;
import javax.inject.Inject;
public class Service {
@Inject
private Message message;
public void showMessage(){
System.out.println(message.getMessage());
}
}
An inquiring mind might ask: What happens if the container is managing more than one bean of
type Message ? For this to be true, Message would have to be an interface that has more than one
concrete implementation. This is where it becomes more interesting . There are several strategies
 
Search WWH ::




Custom Search