Monday, June 04, 2007

Injecting POJOs and using resource injection in POJOs

Java EE 5 greatly simplifies using resources and EJBs by using dependency injection. However this support limits only to managed classes such as EJBs, Interceptors, Servlets, etc. Many applications use helper classes those are regular POJOs. However Java EE 5 / EJB 3 does not require support of dependency injection with regular POJOs or injecting POJOs into managed classes.


In this article, I will discuss about Oracle’s extension of managed POJOs and describes how to use dependency injection such as @Resource or @PersistenceContext with regular POJOs (in OC4J 11 Preview).


This example has a session bean named EmployeeFacade that injects a regular POJO named EmployeeHelper. The EmployeeHelper POJO uses @PersistenceContext to inject an instance of EntityManager.


Using Annotations in regular POJOs


To use dependency injection with regular POJO it does not require any Oracle specific extension. The only requirement is that it must be injected to another managed class by using @oracle.j2ee.annotation.InjectedObject or using Oracle specific descriptor e.g. orion-ejb-jar.xml.



Following is an example of regular POJO that uses dependency injection.


public class EmployeeHelper {
@PersistenceContext
private EntityManager em;
private Employee emp;
public Employee findById(int empNo) {
return ((Employee) em.find(Employee.class, empNo));
}
public Employee saveEmployee(String eName, double sal) {
..
return emp;
}
}

Injecting a POJO
OC4J 11 allows injecting POJOs to a managed class or to another POJO using @oracle.j2ee.annotation.InjectedObject. To inject the EmployeeHelper class into the EmployeeFacade EJB we need the following code:


@Stateless
public class EmployeeFacadeBean implements EmployeeFacade {
@InjectedObject
private EmployeeHelper eh;

public Employee findEmployeeByEmpNo(int empNo) {
return eh.findById(empNo);
}
public int addEmployee(String eName, double sal) {
return eh.saveEmployee(eName,sal).getEmpNo();
}
}


Conclusion

OC4J 11 allows injecting one POJO to another POJO. You can try this with OC4J 11 Preview and let us know what other features you want to see.

2 comments:

Anonymous said...

Stupid question but does this mean that oc4j v10 does not support jpa? This could explain why I have had to develop my adf faces user interface in JDev and then copy to the whole thing to a netbeans project to test pojos.

Debu Panda said...

OC4J 10.1.3.1 fully supports JPA. The POJO injection is an extension to the support