In depth understanding of spring dependency injection

  • 2021-08-31 08:13:24
  • OfStack

IOC & & DI

IOC (Inversion of Control) 1 generally falls into two types: dependency injection DI (Dependency Injection) and dependency lookup (Dependency Lookup)

org. springframework. beans. factory. BeanFactory is the concrete implementation of IOC container and the core interface of Spring IOC container

Spring IOC is responsible for creating objects, managing objects, assembling objects, configuring objects, and managing the entire lifecycle of these objects.

Advantages: Minimize the amount of code applied. Minimum cost and minimum intrusion are achieved by loose coupling. The IOC container supports hungry initialization and lazy loading when loading services

DI dependency injection is an aspect of IOC. It does not need to create an object. It only needs to describe how it is created, which services are required by the component in the configuration file, and then the IOC container is assembled

IOC injection methods: 1, constructor dependency injection 2, Setter method injection 3, factory method injection (rarely used)

Setter method injection

Injecting bean attribute values or dependent objects through the Setter method is the most commonly used injection method


<!-- property To configure properties  
	name Is the attribute name 
 	value Is the attribute value 
-->
<bean id="helloWorld" class="com.zhanghe.study.spring4.beans.helloworld.HelloWorld">
 <property name="name" value="Spring Hello"/>
</bean>

Constructor injection

Constructor injection needs to provide the corresponding constructor


<!--  You can use the index To specify the order of parameters, and the default is in sequence  -->
<bean id="car" class="com.zhanghe.study.spring4.beans.beantest.Car">
 <constructor-arg value=" Ferrari " index="0"/>
 <constructor-arg value="200" index="1"/>
</bean>

However, if there are overloaded constructors, only using index index method can not match accurately, but also need to use type type to distinguish, index and type can be used together


public Car(String brand, double price) {
 this.brand = brand;
 this.price = price;
}

public Car(String brand, int speed) {
 this.brand = brand;
 this.speed = speed;
}

<bean id="car" class="com.zhanghe.study.spring4.beans.beantest.Car">
 <constructor-arg value=" Ferrari " index="0"/>
 <constructor-arg value="20000.0" type="double"/>
</bean>

<bean id="car2" class="com.zhanghe.study.spring4.beans.beantest.Car">
 <constructor-arg value=" Maserati " index="0"/>
 <constructor-arg value="250" type="int"/>
</bean>

Related articles: