Monday, January 25, 2010

JSR 229 - Dependency Injection In Java EE 6

Java EE 6 is coming with new API to support type safe dependency injection that called Contexts and Dependency Injection (CDI). The founder of Hibernate (an open source object/relational mapping solution for Java) Gavin King is leading this JSR to be best dependency injection by using the best features of earlier frameworks like Spring Framework, Google Guice and JBoss Seam.

It is too early to compare the new API with its ancestors. lets just have a brief look at what is available in the API.

Java EE 5 did have a basic form of dependency injection perhaps most appropriately termed resource injection. In Java EE 5 you could inject container resources such as Data Sources, JPA Entity Managers and EJBs via the @Resource, @PersistenceContext, @PersistenceUnit and @EJB annotations into Servlets, JSF backing beans and other EJBs. Java EE 6 is coming with enhanced version of the earlier features plus some additional features to support direct usage of EJBs in JSF backing beans and manage the scope, state, life cycle and context for objects.

Simple Injection
@Stateless
public class MyService {
@Inject
private AnotherService another;
....
}
in this example AnotherSerivice is just a simple POJO that injected to MyService.

Qualifiers
@Stateless
public class MyService {
@Inject
@MyQualifier
private AnotherService another;
....
}

@MyQualifier
public class AnotherServiceImpl implements AnotherService {
....
}

@Qualifier
@Retention(RUNTIME)
@Target({TYPE})
public @interface MyQualifier {}

If there are more than one implementation for a specific service Qualifiers can be used to specify the target implementation.

Scope Identifiers

There are five scope identifiers available in the API.

- ApplicationScoped
An object reference is created only once for the duration of the application and the object is discarded when the application is shut down.
- SessionScoped
An object reference is created for the duration of an HTTP session and is discarded when the session ends.
- RequestScoped
An object reference is created for the duration of the HTTP request and is discarded when the request ends.
- Dependent (Defult Scope)
A dependent reference is created each time it is injected and the reference is removed when the injection target is removed.
- ConversationScoped
A truncated session that defined by application.
@RequestScoped
class MyBean {
....
}

@ApplicationScoped
class MyCache {
....
}

@SessionScoped
class MySessionData {
}
Named Objects

It is possible to define a name for every object that we need to inject. this name can be used by EL in JSP or JSF to retrieve the object.
@RequestScoped @Named("foo")
class MyBean {
....
public String getId() {
....
}
....
}


In the JSP or JSF page you can use the bean by name :

... #{foo.id} ....

And this is it. a short review of Java EE 6 CDI API.
more details about JSR 299 : http://jcp.org/en/jsr/detail?id=299.

No comments:

Post a Comment