Thursday, February 16, 2012

Spring Beans and Dependency Injection - Part 1

In earlier posts, we saw how to manage session state - using cookies and hash tables, and even using jsp and Struts beans.

Trying to manage state ourselves can be difficult, even dangerous. Imagine managing a "Cart" object for each online customer. If you had a bug in your code, you could easily charge the wrong customer the wrong items, and ship them elsewhere! It would be a huge mess even before you realized you had a bug!

Let the professionals handle state.

Like Spring.

Spring Beans & Dependency Injection framework allows you to declare your stateful classes as spring beans. Spring will then take responsibility for creating, managing and destroying these class instances. It will make the right class instance available in the right place.

Let us see this with an example.

Suppose you have an online Shop, with a cart and checkout.

It is critical that the cart that gets filled in during shopping, is the same cart that gets charged at checkout.

Suppose we have a Shop.java class for shopping and a Checkout.java class for checking out. And we have a Cart.java class for the cart.

Both Shop.java and Checkout.java have to access the exact same instance of Cart.java.

If not, clearly, the customer will get charged all wrong. Therefore, we decide not to do this ourselves and let Spring do it for us.

So we declare Shop.java, Checkout.java and Cart.java all as Spring Beans.

We then tell Spring to "inject" the same instance of Cart.java into both Shop.java and Checkout.java.

This is called "Dependency Injection".

Doing all this is called "Bean Configuration" and "Bean Wiring" (telling Spring which Beans to inject). It can be done in an XML file, or as annotations.

In this example, we will use the XML file because it is the more established method.

No comments: