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

Verify, standardize, and correct the Big 4 + more– name, email, phone and global addresses – try our Data Quality APIs now at Melissa Developer Portal!

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.

Developers! Quickly and easily gain access to the tools and information you need! Explore, test and combine our data quality APIs at Melissa Developer Portal – home to tools that save time and boost revenue. Our APIs verify, standardize, and correct the Big 4 + more – name, email, phone and global addresses – to ensure accurate delivery, prevent blacklisting and identify risks in real-time.

Topics:
java ,di ,ioc ,spring

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}