概念
IOC 是面向对象中的一种设计原则,把对象的创建以及对象之间的调用过程交给Spring管理,可以降低耦合度
底层原理
IOC容器底层就是对象工厂,IOC过程主要包括以下几步:
- xml解析 通过xml解析,得到class的路径
- 反射 通过反射方式,根据class的路径创建对象
- 工厂模式 通过工厂模式的方法返回
IOC过程
IOC接口
Spring提供了IOC的两种重要的实现方式(接口):
-
BeanFactory Spring内部使用的接口,一般不提供给外部开发人员使用。加载配置文件的时候不会创建对象,只有当获取、使用的时候才会创建。
-
ApplicationContext BeanFactory接口的子接口,提供更多的功能,面向开发人员使用。加载配置文件的时候就会创建对象。 ApplicationContext有两个实现类:
- FileSystemXmlApplicationContext
ApplicationContext context=new FileSystemXmlApplicationContext(系统全路径);
- ClassPathXmlApplicationCOntext
ApplicationContext context=new ClassPathXmlApplicationContext(类路径);
IOC操作Bean管理
Bean管理主要包括两个操作:
- Spring创建对象
- Spring注入属性 如上的两个Beans管理操作有如下两种实现方式:
- 基于xml配置文件方式实现
- 基于注解方式实现
基于xml配置文件方式
基于xml创建对象
在Spring配置文件中,使用Bean标签,并在其中添加属性就能实现对象的创建
<bean id="user" class="com.Test.User"></bean>
在Bean标签中的常用属性:
- id:唯一标识,可以自定义名称
- class:创建的对象的类的路径
基于xml注入属性
注入属性的方法有两种:
- 使用set方法注入: 首先在该类中创建某变量的set方法,然后在配置文件中配置属性注入,会自动调用对应的set方法。通过property标签,name为属性名称,value为其值
<bean id="user" class="com.Test.User">
<property name="name" value="dwt"></property>
<property name="age" value="18"></property>
</bean>
当value想注入null时,使用null标签
<bean id="user" class="com.Test.User">
<property name="name"><null/></property>
</bean>
- 通过有参构造进行注入 当需要注入的普通属性时,首先创建该类的有参的构造函数,然后在配置文件中进行配置。通过constructor-arg标签,name为属性名称,value为其值
<bean id="user" class="com.Test.User">
<constructor-arg name="name" value="abc"></constructor-arg>
<constructor-arg name="age" value="100"></constructor-arg>
</bean>
当需要注入的是其他类的对象时,先在user类中创建set方法,然后在配置文件中进行配置,主要使用的是property标签的ref属性:
<bean id="user" class="com.Test.User">
<property name="userService" ref="service"></property>
</bean>
<bean id="service" class="com.Test.Service"></bean>
当需要注入的是集合属性时,
<bean id="user" class="com.Test.User">
<property name="account">
<array>
<value>123</value>
<value>456</value>
</array>
</property>
<property name="List">
<list>
<value>123</value>
</list>
</property>
<property name="map">
<map>
<entry key="1" value="123"></entry>
<entry key="2" value="456"></entry>
</map>
</property>
</bean>
当需要注入的是对象的集合时:
<bean id="user" class="com.Test.User">
<property name="List">
<list>
<ref bean="service"></ref>
</list>
</property>
</bean>
<bean id="service" class="com.Test.Service"></bean>
基于注解方式实现
基于注解创建对象
注解:是一种特殊的代码标记,格式:@注解名称(属性名称=属性值,...),可以简化xml配置
在Spring中针对Bean管理创建对象主要包括以下四个注解:
-
@Component
-
@Service
-
@Controller
-
@Repository
这四个注解的功能相同,名称不同主要是供开发人员进行区分
使用注解创建对象的步骤:
- 引入依赖
-
开启组件扫描
-
创建类并在类上面创建对象注解
@Component(value="类名且首字母小写")
基于注解实现属性注入
@AutoWired
@Qualifier
@Resource
@Value