Inversion of Control and Dependency Injection

Let’s take a look at an EJB 2.1 client. We have a stateless session bean that performs simple calculations.

The client needs to know the following items.

  • the JNDI name for the EJB home
  • Where the JNDI naming server is running
  • The protocol used by the JNDI naming server
  • The application server specific JNDI context factory implementation

Then the client needs to do some bookkeeping. The EJB spec uses the Factory Design Pattern to obtain an EJB (actually an EJBObject proxy). In the .85 version of the spec they actually called it the factory but was later changed to the EJB “home”. So, we need to get the home via JNDI and then use the Factory Method to get an instance. Then when we are done with the EJB we need to say so by “removing” it.

Using PortableRemoteObject.narrow to downcast the stubs was a bit of a pain
but it was worse before that method existed. The client needed to know if the stub was
from a CORBA based or RMI based application server. Imagine maintaining that!

The JNDI properties were different for each application server. Here are a few.

For Sun reference implementation

java.naming.factory.initial=com.sun.jndi.cosnaming.CNCtxFactory
java.naming.provider.url=iiop://localhost:105

For Weblogic

java.naming.factory.initial=weblogic.jndi.WLInitialContextFactory
java.naming.provider.url=t3://localhost:7001

For Websphere 5

java.naming.factory.initial=com.ibm.websphere.naming.WsnInitialContextFactory
java.naming.provider.url=iiop://localhost:2809
java.naming.factory.url.pkgs=com.ibm.ws.naming

This was a bit simplified later when you were able to place a jndi.properties file in your classpath.

Or, you could write an ANT target that reads a properties file.

But that is still a pain. What if we could just hand the client the EJB
through a setter? Would that simplify the client?

What do you think? Looks simpler to me!

So now the client is not controlling how it gets the EJB. Something else is controlling that.
You can say that the configuration control has been inverted from the EJB client to another component.
The client is simply injected with it’s EJB dependency.
What component is responsible for this Inversion of Control (IoC)?

That depends.

EJB 3 will have this capability but there are other open source IoC containers available now. In another post I will show you how to do this sort of Dependency Injection (DI) using the Spring Framework which is currently the most popular IoC container available.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.