If you notice you can create and use any type of bat and ball and play cricket with it. All of it is done at runtime. So essentially you are injecting Bat and Ball dependencies into your Cricket object.

Also notice the problems we faced with earlier code are vanished

Code is now decoupled. You can use any Bat and Ball to play cricket.

Testing has also becomes very easy as you can now mock your Bat and Ball objects and test your cricket.

There are two types of dependency injection

Constructor based dependency injection

Setters based dependency injection

What you saw in code above is constructor based dependency injection. Setter based dependency injection is when you use setters instead of constructor to inject dependency. See following example -

"Dependency injection is basically providing the objects that an object needs (its dependencies) instead of having it construct them itself. It's a very useful technique for testing, since it allows dependencies to be mocked or stubbed out."

That's the dependency injection in general. Now lets come to Spring dependency injection.

Spring Dependency Injection

In Spring dependency injection Spring container instantiates and injects dependencies in your instance (also called beans) based on the dependency type or name (more on this later) rather that you instantiating and injecting it yourself.

For values as dependency (like simple String) you can do <property name="brand" ref="MRF"/>

Instead of using property tag you can also use p namespace - <bean id="cricket" class="Cricket" p:brand="MRF" p:bat-ref="myBat" /> (don't forget to add the namespace)

Also note p namespace does not have any schema reference.

Aurowiring

Instead of explicitly providing dependencies to be injected you can autowire them. One simple example is autowiring by type. In this case Spring container will look for bean of dependency type among all beans and inject it. However note if more than one type of such bean exist this will fail.

Another interesting aspect is spring DI using annotations and component scan. Instead of specifying beans you can directly use annotations and ask spring framework to scan those and autowire. You can see the same in next post -