Spring Framework: (IoC) Inversion of control

Introduction

Inversion of control is a design paradigm, and it enables dependency injection patterns. Thus it provides a kind of mechanism that will assemble and collect objects during run time. Additionally, the assembler converts the object into beans to provide an injectable object that will inject to other objects or classes.

Dependency Injection

Dependency Injection is a pattern used by IoC assembler to inject the object’s dependencies on other objects during run time. Rather than describing the dependencies inside of the objects themselves. Injecting object to other objects, meaning we are creating relationship between objects.

Here is the example of the dependency injection pattern for object dependency declaration, which is PetOwner class has Animal dependency:

public class PetOwner {
    private Animal animal;
    public PetOwner(Animal animal) {
        this.animal = animal;
    }
}

And here another example for object-oriented pattern that traditionally used for declaring object dependency:

public class PetOwner {
     private Animal animal;
    public PetOwner() {
        animal = new Animal();    
    }
}

As you noticed, the object instanciation new Animal(); is unnecessary for dependency injection. Therefore, dependency injection handles the object instanciation during run time.

Inversion of Control flow

IoC is the main core of spring architecture. Therefore this architecture handles every spring module, including beans, context, AOP, Aspects, JDBC, ORM, Transaction, Web, Struts, etc..

Spring framework provides different types of configuration metadata including XML-based, Annotation-based, and Java-based configuration. Accordingly, It will handle and interpret by IoC container, therefore, IoC performs initiating and assembling objects. See the image below for the IoC flow:


The illustration shown above is the flow of how IoC interpret configuration metadata to turn it into the injectable objects.

XML-based Configuration

The XML-based configuration is the old way of configuring metadata in spring. It is a type of configuration that places all metadata in the XML file with closing and opening bean tag <bean/> <beans/>.

Here is the basic example of XML-Based configuration setup:

Let’s say we have a dog object that we can use to describe a bean object. Therefore, bean is consider as one of the metadata in spring. Here is the procedure on how we will use XML-based configuration to describe bean object:

You may refer to this post if you don’t have an idea how to setup spring framework:

Create Dog class and place it in new package com.example.demo.model:

public class Dog {
	private String sound;
	public String getSound() {
		return sound;
	}
	public void setSound(String sound) {
		this.sound = sound;
	} 
}

After creating a Dog class, we can now, proceed to XML file creation, and we can name the file AnimalConfiguration.xml. And also make sure you placed it inside of src/main/java path:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd">
  <bean id="dog" class="com.example.demo.model.Dog">
  	<property name="sound" value="Aw Aw Aw (Hello World)"></property>
  </bean>
</beans>

As you can see, we set the value of the field sound using <property> tag. Therefore, we can get the sound value thru Dog bean. And return its value into another object which will print the sound value in the console for the result.

In the QuickStartApplication which is the starting point class, we need to define ClassPathXmlApplicationContext to get the configured bean or metadata in our XML file:

ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("AnimalConfiguration.xml");

and after declaring the ClassPathXmlApplicationContext we can now get the bean object by using getBean method and define which object in the parameter, and after we defining the getBean for dog object, we can now print the dog sound field value in the console:

public class QuickStartApplication {
	public static void main(String[] args) {
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("AnimalConfiguration.xml");
		Dog dog = (Dog)context.getBean("dog");
		System.out.println(dog.getSound());
	}
}
Output:
Aw Aw Aw (Hello World)

Annotation-based Configuration

The annotation-based configuration is alternative way of configuring metadata using an XML file, and only available in the spring 2.5 and above versions. 

The annotation-based configuration helps the developers to reduce their efforts on writing lines of bean tags in the XML file. Therefore, instead of using an XML file to describe and write bean for the object. The developer will just add an annotation in class and method to define java bean then add <context:annotation-config/> tag in XML file.

Here is the basic example of XML-Based configuration setup:

Let’s use @Component annotation in Dog class as example:

@Component
public class Dog {
	private String sound;

	public String getSound() {
		return sound;
	}

	public void setSound(String sound) {
		this.sound = sound;
	} 
}

@Component annotation enables the object to describe it as a spring bean object, and it is equivalent to specifying bean in the XML file. However, this annotation works when performing component-scan using defined classpath during run time.

And replace the XML file value of the previous example with the new XML file below:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns:context="http://www.springframework.org/schema/context"
     xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context.xsd">

   <context:component-scan base-package='com.example.demo.model'></context:component-scan>

</beans>

As you can see, we didn’t need to specify the class name using <bean> tag, and by using the <context:component-scan> tag and the base-package property, we can achieve the same configuration setup in the XML-based example.

The good thing about this configuration is, we don’t need to add a lot of <bean> tags for each object, for example, if we have many objects, and with the help of the annotations we can define bean with the small amount of effort like the example we used above. However, you will encounter null value, after you start the application. Because we didn’t define any properties to set the Dog sound value. but we can do that by adding classes and annotations to set the value. However, we will not discuss that in this tutorial since it is little bit confusing.

Java-based configuration

Java-based is the newest or modern way of configuring metadata, which is available starting with the spring 3.0 version.

This configuration provides features that allow the developers to use java classes. Instead of an XML file Java configuration class can achieve using annotations, including @Configuration, @Bean, @Import, and @DependsOn annotations.

Let’s take the example we used in the previous section, and apply the Java-based configuration:

Add new class name it AnimalConfig, and then apply the @Configuration at the top of the class, so for the spring IoC interprets it as spring configuration:

@Configurable
public class AnimalConfig {
	@Bean
	public Dog getDog() {
		Dog dog = new Dog();
		dog.setSound("Aw Aw Aw (Hello World)");
		return dog;
	}
}

@Configurable is enable to describe bean object to inject it in the java class or object. Instead of describing bean object in XML file or context file.

As you can see, the Dog object was declared as a bean object using @Bean annotation. Therefore, it is equivalent to the <bean> tag we defined in the previous section:

 <bean id="dog" class="com.example.demo.model.Dog">
  	<property name="sound" value="Aw Aw Aw (Hello World)"></property>
 </bean>

At the starting point, we should change the context instantiation using the code below:

public class QuickStartApplication {
	public static void main(String[] args) {
		AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AnimalConfig.class);
		Dog dog = (Dog)context.getBean(Dog.class);
		System.out.println(dog.getSound());
	}
}
Output:
Aw Aw Aw (Hello World)

Conclusion

For the up coming tutorials, I recommended Java-based configuration. Instead of using XML-based and Annotation-based configuration. Since we are focusing in the modern spring examples.

For the next tutorial, we will discuss more annotations and talk about spring MVC framework for spring web development.

2 thoughts on “Spring Framework: (IoC) Inversion of control

  • bape hoodie
    August 8, 2020 at 11:47 pm

    There are definitely plenty of particulars like that to take into consideration. That may be a nice point to deliver up. I provide the thoughts above as normal inspiration however clearly there are questions like the one you bring up where crucial factor will be working in sincere good faith. I don?t know if greatest practices have emerged around issues like that, but I’m sure that your job is clearly recognized as a good game. Both boys and girls feel the influence of only a second抯 pleasure, for the rest of their lives.

  • convese outlet
    August 10, 2020 at 11:08 pm

    I would like to convey my respect for your generosity for individuals that require guidance on this important idea. Your special dedication to getting the message all-around came to be unbelievably useful and has continually enabled guys just like me to reach their goals. Your entire informative recommendations entails this much a person like me and even more to my mates. Many thanks; from everyone of us.

Leave a Reply

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

*
*

This site uses Akismet to reduce spam. Learn how your comment data is processed.

BCF Theme By aThemeArt - Proudly powered by WordPress.
BACK TO TOP