Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Understanding Inversion of Control [Snippet]

DZone's Guide to

Understanding Inversion of Control [Snippet]

This basic introduction will help clarify what Inversion of Control is and how Spring uses it to help find your beans while dealing with dependencies along the way.

· Java Zone ·
Free Resource

Learn how to build stream processing applications in Java-includes reference application. Brought to you in partnership with Hazelcast.

While beginner developers quickly learn to understand Dependency Injection, they might have more difficulty knowing what Inversion of Control is actually about.

So, we are going to go over Inversion of Control (IoC) in the simplest manner possible.

To begin with, let's go over how Dependency Injection works:

  • In EJB container-managed applications, when we want to resolve a dependency such as Session Beans, we look for that bean by looking into the JNDI tree. So it's us/our code that looks and find a dependency.

Spring resolves our dependency using IoC. That is the Spring container that finds a bean, pushes it wherever it is required, and resolves the dependency. We don't look it up ourselves to find them.

The following code sample will help us understand the concept:

<bean name="customerRepository"
    class="org.ashah.repository.CustomerRepositoryHibernate"/>

<bean name="customerService"
    class="org.ashah.service.CustomerServiceImpl">
    <property name="customerRepository" ref="customerRepository"></property>
</bean>


In the code above, if you are familiar with Spring, we have declared two beans — customerRepository and customerService. We are declaring where we need our dependency. In this case, we want to resolve the dependency of customerService's property, customerRepository.

That is it. We are not finding dependencies, we are just declaring where we need them.

Welcome to Inversion of Control.

Check out the code on GitHub here.

Learn how to build distributed stream processing applications in Java that elastically scale to meet demand- includes reference application.  Brought to you in partnership with Hazelcast.

Topics:
java ,di ,ioc ,spring

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}