Java Reference
In-Depth Information
import javax.inject.Named;
class UserService {
@Inject
@Named("UserDataRepositoryMongo")
private UserDataRepository udr;
public void persistUser(User user) {
udr.save(user);
}
}
An explicit annotation of the Mongo implementation is required by a corresponding @Named annotation
appropriately named. In Listing 5‐9, the Mongo implementation of the UserDataRepository interface
is annotated with the same String name as that used to disambiguate the injected implementation in
Listing 5‐8.
LISTING 5‐9: The concrete implementation requires an @Named annotation
package com.devchronicale.di;
import javax.inject.Named;
@Named("UserDataRepositoryMongo")
public class UserDataRepositoryMongo implements UserDataRepository {
@Override
public void save(User user) {
// Persistence code here
}
}
The use of Strings to identify dependencies is legacy because it is not type safe and is discouraged
in the CDI specii cation JSR‐299. However, there is a use of the @Named annotation that avoids the
need to use String identii ers at the point of injection.
@Inject @Named
private UserDataRepository UserDataRepositoryMongo;
In Listing 5‐9, the name of the implementation to inject is inferred from the name of the i eld
UserDataRepositoryMongo . What is effectively happening is that @Named is being replaced by
@Named("UserDataRepositoryMongo") .
Context and Dependency Injection (CDI)
Context and Dependency Injection (CDI) brought full‐l edged dependency injection and context
support to the Java EE platform, which used to be EJB specii c and far more limited. After EJB 3
was introduced, JBoss introduced Seam (a web application framework), which had become quite
popular, by supporting direct interaction between JavaServer Faces (JSF) and JavaBeans as well as
EJB. The success of Seam led to the design of JSR299, WebBeans. Just as Hibernate, a famous Java
Persistance Framework, inspired Java Persistence API (JPA) standardization, Seam inspired and
formed the core implementation of CDI.
 
Search WWH ::




Custom Search