Rick has posted 25 posts at DZone. You can read more from them at their website. View Full User Profile

Spring Dependency Injection - An Introductory Tutorial

11.11.2008
| 191562 views |
  • submit to reddit

This article discusses dependency injection in a tutorial format. It covers some of the newer features of Spring DI such as annotations, improved XML configuration and more.

Dependency Injection

Dependency Injection (DI) refers to the process of supplying an external dependency to a software component. DI can help make your code architecturally pure. It aids in design by interface as well as test-driven development by providing a consistent way to inject dependencies. For example, a data access object (DAO) may depend on a database connection. Instead of looking up the database connection with JNDI, you could inject it.

One way to think about a DI container like Spring is to think of JNDI turned inside out. Instead of an object looking up other objects that it needs to get its job done (dependencies), a DI container injects those dependent objects. This is the so-called Hollywood Principle, “Don't call us” (lookup objects), “we’ll call you” (inject objects).

If you have worked with CRC cards you can think of a dependency as a collaborator, i.e., an object that another object needs to perform its role.
Let's say that you have an automated teller machine (ATM) and it needs the ability to talk to a bank. It uses what it calls a transport object to do this. In this example, a transport object handles the low-level communication to the bank.

This example could be represented by either of the  two interfaces as follows:

AutomatedTellerMachine interface

package com.arcmind.springquickstart;

import java.math.BigDecimal;

public interface AutomatedTellerMachine {
        void deposit(BigDecimal bd);
        void withdraw(BigDecimal bd);
}

 

ATMTransport interface

package com.arcmind.springquickstart;

public interface ATMTransport {
        void communicateWithBank(byte [] datapacket);
}

Now the AutomatedTellerMachine needs a transport to perform its intent, namely withdraw money and deposit money. To carry out these tasks, the AutomatedTellerMachine may depend on many objects and collaborates with its dependencies to complete the work.

An implementation of the AutomatedTellerMachine may look like this:

AutomatedTellerMachine implementation:

package com.arcmind.springquickstart;

import java.math.BigDecimal;

public class AutomatedTellerMachineImpl implements AutomatedTellerMachine{
        
        private ATMTransport transport;
        
        public void deposit(BigDecimal bd) {
          ...
                transport.communicateWithBank(...);
        }

        public void withdraw(BigDecimal bd) {
          ...
                transport.communicateWithBank(...);
        }

        public void setTransport(ATMTransport transport) {
                this.transport = transport;
        }
        
}
 

The AutomatedTellerMachineImpl does not know or care how the transport withdraws and deposits money from the bank. This level of indirection allows us to replace the transport with different implementations such as in the following example:

Three example transports: SoapAtmTransport, StandardAtmTransport and SimulationAtmTransport

package com.arcmind.springquickstart;

public class SoapAtmTransport implements ATMTransport {

        public void communicateWithBank(byte[] datapacket) {
           ...
        }

}
package com.arcmind.springquickstart;

public class StandardAtmTransport implements ATMTransport {

        public void communicateWithBank(byte[] datapacket) {
          ...
        }

}

 

package com.arcmind.springquickstart;

public class SimulationAtmTransport implements ATMTransport {

        public void communicateWithBank(byte[] datapacket) {
                ...
        }

}

 

Notice the possible implementations of the ATMTransport interface. The AutomatedTellerMachineImpl does not know or care which transport it uses. Also, for testing and developing, instead of talking to a real bank, notice that you can use the SimulationAtmTransport.



About the author

Rick Hightower is CTO of Mammatus and is an expert on Java and Cloud Computing. Rick is invovled in Java CDI advocacy and Java EE. CDI Implementations - Resin Candi - Seam Weld - Apache OpenWebBeans

Published at DZone with permission of its author, Rick Hightower.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Comments

Murphree Mukada replied on Thu, 2008/11/27 - 7:48am

Brilliant! Concise and clear. Thanks a million Rick.

Rick Hightower replied on Sun, 2008/11/30 - 6:33pm in response to: George Jiang

The Spring AOP article has been written and is waiting to be copy edited.

Viraf Karai replied on Sat, 2009/02/21 - 3:14pm

Well written, but it might still be a tad difficult for newcomers to Spring to grasp fully.

I'm not in the anti-XML camp, so I don't feel very comfortable with this new trend towards using annotations willy-nilly. In fact I feel that it diminishes the ability to view the big picture. I do like the new 'context' and 'p' namespaces. Some of the annotations like @Required and @Transactional have been well-thought out by the SpringSource folks and I commend them for that.

Just one final note and it's not meant to be a sales pitch - IntelliJ IDEA 8.x has brilliant Spring support and provides really good code completion as well as linking Java interfaces with Spring bean definitions. I've been using it for about 8 months now and am continually amazed at it's capabilities.

Looking forward to your future articles - especially AOP - a great passion of mine.

Rick Reumann replied on Tue, 2009/09/01 - 2:54pm

I'm really curious though, how often do people have that many different implementations at application startup time? I've been using Spring and Guice for a while now and often when I've completed my app I look back and wonder "ok, what did I really gain here having my concrete implemenations defined in an xml or single Java file?"

 I don't care much about using Mock objects in Testing either, but if I did, I could definitely see the advantage of DI there. 

 Of course I like containers doing some DI for me, like the EJB3 DI stuff etc, but in your typical CRUD app I simply find that I've added one more layer of abstraction that isn't needed. In the early days I was also always a purist and coded everything to an Interface - but in real life, how often, for example, are you swapping out Service class or DAO implemnations? 

 I feel like a heretic and wondering if I'm alone :)

 

Pradeep Kumar replied on Wed, 2012/09/19 - 12:59pm

Very nice, no words thanks much..!!

But please add spring MVC 3.0 also.

Krishna Pokala replied on Tue, 2012/10/02 - 9:08am

Superb intro to DI. Thanks Rick

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.