SpringIoC学习总结:
IoC 控制反转 为什么是反转呢,因为传统意义上 我们是通过new 的方式 创建对象,反转 是通过反射的方式 进行对象的操作(即对bean的操作)。
DI 依赖注入,通过反射后将值进行依赖注入 ,即对属性赋值。
IoC的实现方式是DI,实现原理是反射。*
IDEA四个依赖包
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.18.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.3.18.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.18.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.3.18.RELEASE</version>
</dependency>
eclipse 依赖包
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.0.3.RELEASE</version>
</dependency>
xml配置文件
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="student" class="com.qust.Student" ***scope="singleton"***>
<property name="sid" value="01"></property>
<property name="name" value="qw"></property>
<property name="sex" value="true"></property>
<property name="score" value="100"></property>
<property name="birth" ref="birth"></property>
</bean>
<bean id="birth" class="com.qust.Birthday">
<property name="year" value="2020"></property>
<property name="month" value="12"></property>
<property name="day" value="20"></property>
</bean>
</beans>
DI依赖注入的三种方式
1.通过setter方式进行注入
通过反射获得的对象 调用setter方法设置
2.通过构造方法
通过对xml文件中constructor-arg设置有参构造(如果不设置有参构造注入,默认下都是无参构造)
<bean id="birth1" class="com.qust.Birthday">
<constructor-arg name="year" value="2020"></constructor-arg>
<constructor-arg name="month" value="12"></constructor-arg>
<constructor-arg name="day" value="20"></constructor-arg>
</bean>
3.通过p命名表达式 类似于jstl
前提在xml中加入 xmlns:p="http://www.springframework.org/schema/p"
scope=“singleton” 默认情况下是单列模式