Inversion of Control and Dependency Injection with Spring
What Is Inversion of Control?
Inversion of Control is a principle in software engineering which transfers the control of objects or portions of a program to a container or framework. We most often use it in the context of object-oriented programming.
In contrast with traditional programming, in which our custom code makes calls to a library, IoC enables a framework to take control of the flow of a program and make calls to our custom code. To enable this, frameworks use abstractions with additional behavior built in. If we want to add our own behavior, we need to extend the classes of the framework or plugin our own classes.
The advantages of this architecture are:
- decoupling the execution of a task from its implementation
- making it easier to switch between different implementations
- greater modularity of a program
- greater ease in testing a program by isolating a component or mocking its dependencies, and allowing components to communicate through contracts
We can achieve Inversion of Control through various mechanisms such as: Strategy design pattern, Service Locator pattern, Factory pattern, and Dependency Injection (DI).
The Spring IoC Container
Bean Factory
A BeanFactory is like a factory class that contains a collection of beans. The BeanFactory holds Bean Definitions of multiple beans within itself and then instantiates the bean whenever asked for by clients.
BeanFactory is able to create associations between collaborating objects as they are instantiated. This removes the burden of configuration from bean itself and the beans client. BeanFactory also takes part in the life cycle of a bean, making calls to custom initialization and destruction methods.
- Resource resource=new ClassPathResource(“applicationContext.xml”);
- BeanFactory factory=new XmlBeanFactory(resource);
Application Context
The ApplicationContext interface is built on top of the BeanFactory interface. It adds some extra functionality than BeanFactory such as simple integration with Spring’s AOP, message resource handling (for I18N), event propagation, application layer specific context (e.g. WebApplicationContext) for web application. So it is better to use ApplicationContext than BeanFactory.
- ContextPathXmlAppliationContext : It Loads context definition from an XML file located in the classpath, treating context definitions as classpath resources. The application context is loaded from the application’s classpath by using the code.
ApplicationContext context = new
ClassPathXmlApplicationContext("bean.xml");
2. FileSystemXmlAppliationContext : It loads context definition from an XML file in the filesystem. The application context is loaded from the file system by using the code .
ApplicationContext context = new
FileSystemXmlApplicationContext("bean.xml");
3. XmlWebApplicationContext : It loads context definition from an XML file contained within a web application.
What Is Dependency Injection?
Dependency injection is a pattern we can use to implement IoC, where the control being inverted is setting an object’s dependencies.
Connecting objects with other objects, or “injecting” objects into other objects, is done by an assembler rather than by the objects themselves.
Here’s how we would create an object dependency in traditional programming:
public class Store {
private Item item;
public Store() {
item = new ItemImpl1();
}
}
In the example above, we need to instantiate an implementation of the Item interface within the Store class itself.
By using DI, we can rewrite the example without specifying the implementation of the Item that we want:
public class Store {
private Item item;
public Store(Item item) {
this.item = item;
}
}
In the next sections, we’ll look at how we can provide the implementation of Item through metadata.
Both IoC and DI are simple concepts, but they have deep implications in the way we structure our systems, so they’re well worth understanding fully.
Constructor-Based Dependency Injection
In the case of constructor-based dependency injection, the container will invoke a constructor with arguments each representing a dependency we want to set.
Spring resolves each argument primarily by type, followed by name of the attribute, and index for disambiguation. Let’s see the configuration of a bean and its dependencies using annotations:
@Configuration
public class AppConfig { @Bean
public Item item1() {
return new ItemImpl1();
} @Bean
public Store store() {
return new Store(item1());
}
}
The @Configuration annotation indicates that the class is a source of bean definitions. We can also add it to multiple configuration classes.
We use the @Bean annotation on a method to define a bean. If we don’t specify a custom name, then the bean name will default to the method name.
For a bean with the default singleton scope, Spring first checks if a cached instance of the bean already exists, and only creates a new one if it doesn’t. If we’re using the prototype scope, the container returns a new bean instance for each method call.
Another way to create the configuration of the beans is through XML configuration:
<bean id="item1" class="org.baeldung.store.ItemImpl1" />
<bean id="store" class="org.baeldung.store.Store">
<constructor-arg type="ItemImpl1" index="0" name="item" ref="item1" />
</bean>
Setter-Based Dependency Injection
For setter-based DI, the container will call setter methods of our class after invoking a no-argument constructor or no-argument static factory method to instantiate the bean. Let’s create this configuration using annotations:
@Bean
public Store store() {
Store store = new Store();
store.setItem(item1());
return store;
}
We can also use XML for the same configuration of beans:
<bean id="store" class="org.baeldung.store.Store">
<property name="item" ref="item1" />
</bean>
Field-Based Dependency Injection
In case of Field-Based DI, we can inject the dependencies by marking them with an @Autowired annotation:
public class Store {
@Autowired
private Item item;
}
Autowiring Dependencies
Wiring allows the Spring container to automatically resolve dependencies between collaborating beans by inspecting the beans that have been defined.
There are four modes of autowiring a bean using an XML configuration:
- no: the default value — this means no autowiring is used for the bean and we have to explicitly name the dependencies.
- byName: autowiring is done based on the name of the property, therefore Spring will look for a bean with the same name as the property that needs to be set.
- byType: similar to the byName autowiring, only based on the type of the property. This means Spring will look for a bean with the same type of the property to set. If there’s more than one bean of that type, the framework throws an exception.
- constructor: autowiring is done based on constructor arguments, meaning Spring will look for beans with the same type as the constructor arguments.
For example, let’s autowire the item1 bean defined above by type into the store bean:
@Bean(autowire = Autowire.BY_TYPE)
public class Store {
private Item item; public setItem(Item item){
this.item = item;
}
}
We can also inject beans using the @Autowired annotation for autowiring by type:
public class Store {
@Autowired
private Item item;
}
If there’s more than one bean of the same type, we can use the @Qualifier annotation to reference a bean by name:
public class Store {
@Autowired
@Qualifier("item1")
private Item item;
}
Now let’s autowire beans by type through XML configuration:
<bean id="store" class="org.baeldung.store.Store" autowire="byType"> </bean>
Next, let’s inject a bean named item into the item property of store bean by name through XML:
<bean id="item" class="org.baeldung.store.ItemImpl1" /><bean id="store" class="org.baeldung.store.Store" autowire="byName">
</bean>
We can also override the autowiring by defining dependencies explicitly through constructor arguments or setters.