Java Reference
In-Depth Information
things, which is to use an XML configuration file. You can still use this, but modern Spring
practice is to use Java annotations to configure the dependencies.
Annotations are also used in the Java Enterprise Edition Contexts and Dependency Injection
(CDI). Although this is most widely used in web applications, we'll reuse the same example,
using the open source “Weld” implementation of CDI. CDI is quite a bit more powerful than
Spring's DI; because in CDI we don't even need to know the class from which a resource is
being injected, we don't even need the interfaces from the Spring example! First, the “Con-
troller” or main program, which requires a Weld-specific import or two because CDI was ori-
ginally designed for use in enterprise applications:
CDI ConsoleViewer.java
public
public class
class ConsoleViewer
ConsoleViewer implements
implements View {
@Inject @MyModel
private
private String message ;
@Override
public
public void
void displayMessage () {
System . out . println ( message );
}
}
The View interface is shared between both implementations. The ConsoleViewer imple-
mentation is similar too, except it isn't coupled to the Model; it just asks to have a String in-
jected. In this simple example there is only one String in the application; in a larger app you
would need one additional annotation to specify which string to inject:
CDI ConsoleViewer.java
public
public class
class ConsoleViewer
ConsoleViewer implements
implements View {
@Inject @MyModel
private
private String message ;
@Override
public
public void
void displayMessage () {
System . out . println ( message );
}
}
Where does the injected String come from? From the Model, as before:
Search WWH ::




Custom Search