Spring's Inversion of Control and Dependency Injection

IoC (Inversion of Control): Inversion of Control
It means that the acquisition method of objects in the program is reversed, from the original constructor method to the creation and injection of third-party frameworks.                                                                        
The right to create objects is reversed to the Spring container: the container creates instances according to the configuration file and maintains the dependencies between each instance.
In-depth understanding: IoC can be regarded as the sublimation of the factory pattern, and IoC can be regarded as a large factory, but the objects to be generated in this large factory are all defined in the XML file, and then use Java's "" "Reflection" programming to generate corresponding objects based on class names and types given in XML.
Reflection: Generally speaking, it is to generate an object based on the given class name. This way of programming allows objects to decide which object to generate when they are generated.

DI (Dependency Injection)—another way of expressing IoC
That is, the component accepts resource injection from the container in some predefined ways (such as setter methods).
To put it bluntly, Spring injects object dependency properties through configuration during the process of creating objects. Compared to IoC, this formulation is more straightforward.
IoC is an idea, and DI is the main technical way to realize IoC.

The way of dependency injection:                                                                                                                                                                                              
①setter injection (usually also called property injection) ----------------------------------------- ---------------------------------------
That is, the property value of the bean and the dependent object are injected through the set method. This method requires the set method of the injected property.
First create an entity class UserService, define two member variables name and age, and its set method. Then you can use property injection in the configuration file:

<bean id="emp" class="mypack.entity.Emp">
      		<property name="id" value="11"></property>
      		<property name="name" value="lbj"></property>
      		<property name="age" value="21"></property>
      		<property name="salary" value="5000"></property>
      </bean>

②Constructor injection --------------------------------------------- ----------------------
By injecting bean property values ​​or dependent objects through the constructor, it ensures that the bean instance can be used after instantiation. This way of writing is used when the parameters of the constructor in a class are other classes.
For example, in the constructor of the EmpDao class, the parameter is of type Emp, but I have not created a set method for it, so it cannot support setter injection.

<bean id="empDao" class="mypack.dao.EmpDao">
      		<constructor-arg ref="emp"></constructor-arg>
      </bean>
<bean id="car">
    <constructor-arg value="Audi"/>
    <constructor-arg value="BWM"/>
</bean>

Spring's autowiring
The Spring IoC container can autowire (autowire) the relationship between cooperating beans. Autowire can be set for a single bean. Its convenience is to reduce XML injection configuration. In an XML file, the autowire attribute can be declared in an element.

①byName ---------------------------------------------------------------------------------------------
The IoC container will find the id of the corresponding JavaBean according to the corresponding attribute name in the set method. So the id and property name of the target bean must be set exactly the same.

②byType -----------------------------------------------------------------------------------------------
The IoC container will find the corresponding JavaBean according to the type of the parameter in the set method, that is to say, the parameter type of the set method must be the same as the class type of the bean to match.

The above two methods essentially construct the corresponding set method through reflection, and then execute the set method.

③constructor ---------------------------------------------------------------------------------------------
IoC容器会根据有参构造器中参数类型找到对应的JavaBean。
当bean中存在多个构造器时,此种方式将会很复杂,故不推荐使用。

④autodetect -----------------------------------------------------------------------------------------------
先通过constructor,若没有匹配到再通过byType匹配。


以上学到的bean的配置都是基于XML的方式,接下来学习基于注解的方式配置bean。


组件扫描(component scanning)

Spring能够从classpath下自动扫描、侦测和实例化具有特定注解的组件。
使用组件扫描,首先需要指定扫描类路径:                                                                                                                                                           
<context:component-scan base-package="com.springdemo"></context:component-scan>
特定组件包括:
@Component:基本注解,标识了一个受Spring管理的组件
@Repository:标识持久层组件
@Service:标识业务层组件
@Controller:标识控制层组件

对于扫描到的组件,Spring也有默认的命名策略:
使用非限定类名,第一个字母小写,作为默认的id值,例如UserService类的默认bean的id值是"userService"。
我们也可以在注解标记中自定义id,例如:@Component("userService1")。

指定组件的作用域 ---------------------------------------------------------------------------------------------
通常受Spring管理的组件,默认作用域是singleton,我们可以使用@Scope注解指定作用域,例如:@Scope("prototype")

初始化回调和销毁回调注解 -----------------------------------------------------------------------------------
@PostConstruct和@PreDestroy分别对应初始化回调和销毁回调。

基于注解注入bean的属性

元素还会自动注册AutowiredAnnotationBeanPostProcessor实例,该实例可自动装配具有 @Autowired、@Resource和@Inject注解的属性

①@Resource ---------------------------------------------------------------------------------------------

可以用在字段或属性的set方法上面,默认按照byName自动注入。

@Resource注解有两个属性比较重要,分别是name和type,name属性解析为bean的名字,而type属性则解析为bean的类型。如果使用name属性,则按byName自动注入,而使用type属性,则按byType自动注入。

@Resource默认按byName装配。名称可以通过name属性来指定,如@Resource(name="userDao"),如果没有指定name属性,当注解标记在字段上,则取字段名称作为bean名称寻找依赖对象,当注解标注在属性的set方法上,则默认按属性名作为bean名称寻找依赖对象。

注意:如果没有指定name属性,并且按照默认的名称仍找不到依赖对象,@Resource会会退到按类型装配。但一旦指定了name属性,就只能按名称装配了。

②@Autowired   ---------------------------------------------------------------------------------------------

自动装配具有兼容类型的单个bean属性,即按照byType自动注入。
可应用于构造器、字段和set方法上面。
默认情况下,要求依赖对象必须存在,如果要允许null值,可以设置它的required属性为false,如:@Autowired(required=false)。
默认情况下,当IoC容器里存在多个类型兼容(如一个接口下有多个实现类)的bean时,通过类型的自动装配将无法工作,此时可以结合@Qualifier注解按名称装配。
@Qualifier的意思是合格者,通过这个标识表明了哪个实现类才是我们需要的。
@Qualifier可以标注在@Autowire注解下面,也可以对方法的入参标注。
例如:public void setUser(@Qualifier("service") User user){……}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325764126&siteId=291194637