Dependecny Injection(DI) to Access EJBs

There are two ways to access the EJBs: 1. JNDI 2. DI

Advantages:

  1. Removes JNDI lookups
  2. DI can inject this:
    1. @EJB
    2. @Resource, @PersistenceContext, @EntityManager

DI is supported within:

  1. Enterprise Java Beans
  2. Servlets/JSPs/Filters/Managed Beans/
  3. Applicaiton Client Container clients

Annotations:

@EJB

Example of dependency injection EJB -> Servlet

// this is servlet
@WebServlet(name="DICalculator", urlPatterns = {"/DICalculator"})
public class DICalculatorServerlet extends HttpServlet {

// Line below injects RemoteCalculator bean into this servlet
@EJB
private RemoteCalculator calculator;
// now we can use the injected object
int sum = calculator.multiply(5,5);
RequestDispatcher dispatcher = request.getRequestDispatcher("calc-result.jsp");

@Resource

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s