IOC容器
1.IOC思想
IOC:Inversion of Control,翻译过来就是反转控制。
当我们要使用一个对象的时候,以前我们是自己手动通过new来进行创建一个对象。使用反转控制后,我们需要哪个对象,IOC容器就会为我们提供该对象(怎么实现的呢?就是通过依赖注入来为对象进行赋值)。我们直接拿来用就可以了。
2.DI
DI:Dependency Injection,翻译过来是依赖注入。
DI 是 IOC 的另一种表述方式:即组件以一些预先定义好的方式(例如:setter 方法)接受来自于容器的资源注入。说白了就是为Spring所管理的对象中的属性来进行赋值。
注入:为当前对象所依赖的对象进行赋值的过程。
IOC 就是一种反转控制的思想, 而 DI 是对 IOC 的一种具体实现。
3.IOC容器在Spring中的实现
IOC 容器中管理的组件也叫做 bean。在创建 bean 之前,首先需要创建 IOC 容器。Spring 提供了 IOC 容器的两种实现方式:
1.BeanFactory
这是 IOC 容器的基本实现,是 Spring 内部使用的接口。面向 Spring 本身,不提供给开发人员使用。
2.ApplicationContext
BeanFactory 的子接口,面向 Spring 的使用者,几乎所有场合都使用 ApplicationContext 而不是底层的 BeanFactory。
3.ApplicationContext的主要实现类
ClassPathXmlApplicationContext |
通过读取类路径下的
XML
格式的配置文件创建
IOC
容器对象
|
FileSystemXmlApplicationContext |
通过文件系统路径读取
XML
格式的配置文件创建
IOC
容器对象
|
ConfigurableApplicationContext |
ApplicationContext
的子接口,包含一些扩展方法refresh() 和
close()
,让
ApplicationContext
具有关闭和刷新容器的能力。
|
WebApplicationContext |
专门为
Web
应用准备,基于
Web
环境创建
IOC
容器对象,并将对象引入存入 ServletContext
域中。
|
入门案例
1.创建maven工程
2.在pom.xml中引入依赖
<dependencies>
<!-- 基于Maven依赖传递性,导入spring-context依赖即可导入当前所需所有jar包 -->
<!--context:上下文-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.1</version>
</dependency>
<!-- junit测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
3.创建helloworld类:
public class HelloWorld {
public void sayHello(){
System.out.println("hello,spring");
}
}
4.创建Spring配置文件在配置文件中配置bean
<!--
配置HelloWorld所对应的bean,即将HelloWorld的对象交给Spring的IOC容器管理
bean:配置一个bean对象,将对象交给IOC容器管理
属性:
id:设置bean的唯一标识
class:设置bean对象所对应的类型的全类名
一个bean对应一个对象
-->
<bean id="helloworld" class="spring.pojo.HelloWorld"></bean>
5.创建测试类
public class HelloWorldTest {
@Test
public void test(){
//获取IOC容器
//configLocation:配置路径(配置文件的路径)
//resources和java最终会加载到同一个目录(类路径)下,所以可以直接写文件名
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//获取IOC容器中的bean 根据name获取bean--name即bean的id
//由于是根据bean的id获取的bean,不知道类型,要做一个强转
HelloWorld helloworld = (HelloWorld) ac.getBean("helloworld");
helloworld.sayHello();
}
}