Topic 4:- IOC (Inversion of Control) & 4 Types of Autowirings

image 2

Play Store Application link – Spring Framework in 9 steps – Apps on Google Play

Understanding Inversion of Control (IoC) in Spring

IoC is a design principle where the control of creating objects is transferred from the application code to a configuration file (either XML or annotations). This helps to decouple the code and manage dependencies more effectively.

Dependency Injection (DI)

In Spring, IoC is achieved through Dependency Injection (DI). Instead of instantiating objects directly, you configure how they should be created and wired together in a separate configuration file.

Example Program Without IoC

Here’s how you might implement a simple text editor without IoC:

public class Main {
    public static void main(String[] args) {
        // Without IoC: Creating dependencies manually (tight coupling)
        SpellChecker spellChecker = new SimpleSpellChecker();
        TextEditor textEditor = new TextEditor(spellChecker);
        textEditor.spellCheck();
    }
}
public class TextEditor {
    private SpellChecker spellChecker;
    public TextEditor(SpellChecker spellChecker) {
        this.spellChecker = spellChecker;
    }
    public void spellCheck() {
        spellChecker.checkSpelling();
    }
}
public interface SpellChecker {
    void checkSpelling();
}
public class SimpleSpellChecker implements SpellChecker {
    @Override
    public void checkSpelling() {
        System.out.println("Checking spelling using SimpleSpellChecker...");
    }
}
public class AdvancedSpellChecker implements SpellChecker {
    @Override
    public void checkSpelling() {
        System.out.println("Checking spelling using AdvancedSpellChecker...");
    }
}

Example Program With IoC

Now, let’s see how we can achieve the same functionality using Spring IoC with XML configuration:

applicationContext.xml

<beans>
    <bean id="textEditor" class="com.example.TextEditor">
        <constructor-arg ref="advancedSpellChecker"/>
    </bean>
    <bean id="simpleSpellChecker" class="com.example.SimpleSpellChecker"/>
    <bean id="advancedSpellChecker" class="com.example.AdvancedSpellChecker"/>
</beans>

Main.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
    public static void main(String[] args) {
        // With IoC: Beans are created and wired by Spring
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        TextEditor textEditor = context.getBean("textEditor", TextEditor.class);
        textEditor.spellCheck();
    }
}

Benefits of IoC

Using IoC makes managing dependencies easier, especially in large applications with many classes. It promotes loose coupling and simplifies testing.

Types of IoC Containers

  1. BeanFactory: Basic container for managing beans. It uses lazy initialization (beans are created on demand).
  2. ApplicationContext: A more advanced container that supports features like event propagation and internationalization. It uses eager initialization (all beans are created at startup).

Types of Dependency Injection

  1. Constructor-Based DI:
   public class MyBean {
       private final Dependency dependency;
       public MyBean(Dependency dependency) {
           this.dependency = dependency;
       }
   }

XML Configuration:

   <bean id="myBean" class="com.example.MyBean">
       <constructor-arg ref="dependency"/>
   </bean>
  1. Setter-Based DI:
   public class MyBean {
       private Dependency dependency;
       public void setDependency(Dependency dependency) {
           this.dependency = dependency;
       }
   }

XML Configuration:

   <bean id="myBean" class="com.example.MyBean">
       <property name="dependency" ref="dependency"/>
   </bean>

Github project link – https://github.com/kuldeep101990/SpringIOC_DependencyInjection


Types of AutoWiring –

Autowire ModeDescriptionMatching CriteriaWhen to Use
No /DefaultNo automatic wiring / Uses global container settingExplicitly wired by the developer / Depends on container configurationFor full manual control over wiring. / For consistency with global settings.
byNameMatches bean ID with property nameProperty name = Bean IDWhen bean IDs match property names.
byTypeMatches type of beanSingle matching bean typeWhen only one bean of a type exists.
constructorMatches constructor parametersConstructor arguments = Bean types/valuesFor mandatory dependencies via constructor.

1. Default Autowiring

XML Based: Github project link – https://github.com/kuldeep101990/SpringDefaultAutoWiringXml

Annotation Based: Github project link – https://github.com/kuldeep101990/SpringDefaultAutoWiringAnnotation


2. Autowiring by Name

XML way: Github project link – https://github.com/kuldeep101990/SpringAutoWiringByNameXml

Annotation way: Github project link – https://github.com/kuldeep101990/SpringAutoWiringByNameAnnotation


3. Autowiring by Type

XML way: Github project link – https://github.com/kuldeep101990/SpringAutoWiringByTypeXml

Annotation way: Github project link – https://github.com/kuldeep101990/SpringAutoWiringByTypeAnnotation


4. Autowiring by Constructor

XML way: Github project link – https://github.com/kuldeep101990/SpringAutoWiringByConstructorXml

Annotation way: Github project link – https://github.com/kuldeep101990/SpringAutoWiringByConstructorAnnotation

Leave a Reply

Your email address will not be published. Required fields are marked *