一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第14天,点击查看活动详情。
IOC的思想参考上一篇文章
IOC容器在Spring中的实现
①BeanFactory
这是 IOC 容器的基本实现,是 Spring 内部使用的接口。面向 Spring 本身,不提供给开发人员使用。
②ApplicationContext
BeanFactory 的子接口,提供了更多高级特性。面向 Spring 的使用者,几乎所有场合都使用 ApplicationContext 而不是底层的 BeanFactory。
以后在 Spring 环境下看到一个类或接口的名称中包含 ApplicationContext,那基本就可以断定,这个类或接口与 IOC 容器有关。
③ApplicationContext的主要实现类
| 类型名 | 简介 |
|---|---|
| ClassPathXmlApplicationContext | 通过读取类路径下的 XML 格式的配置文件创建 IOC 容器对象 |
| FileSystemXmlApplicationContext | 通过文件系统路径读取 XML 格式的配置文件创建 IOC 容器对象 |
| ConfigurableApplicationContext | ApplicationContext 的子接口,包含一些扩展方法 refresh() 和 close() ,让 ApplicationContext 具有启动、关闭和刷新上下文的能力。 |
| WebApplicationContext | 专门为 Web 应用准备,基于 Web 环境创建 IOC 容器对象,并将对象引入存入 ServletContext 域中。 |
无参构造器
Spring 底层默认通过反射技术调用组件类的无参构造器来创建组件对象,这一点需要注意。如果在需要无参构造器时,没有无参构造器,则会抛出下面的异常:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'happyComponent1' defined in class path resource [applicationContext.xml]: Instantiation of bean failed;
nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.atguigu.ioc.component.HappyComponent]: No default constructor found;
nested exception is java.lang.NoSuchMethodException: com.atguigu.ioc.component.HappyComponent.()
所以对一个JavaBean来说,无参构造器和属性的getXxx()、setXxx()方法是必须存在的,特别是在框架中。
入门案例
①导入依赖
导入SpringIOC相关依赖
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
②编写配置文件
在resources目录下创建applicationContext.xml文件,new > xml config > spring config,文件名可以任意取。但是建议叫applicationContext。
内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--
classs:配置类的全类名
id:配置一个唯一标识
-->
<bean class="com.dao.impl.StudentDaoImpl" id="studentDao" >
</bean>
</beans>
[可选] 配置IDEA项目工程中的应用上下文
粘贴了上面这段 xml 后,IDEA 会弹出一段提示:
由此可见 IDEA 是多么的智能,它意识到你要在工程中添加 SpringFramework 的配置文件,它就想让你把这个配置文件配置到 IDEA 的项目工作环境下,那咱只需要按照提示,点击 Configure application context ,随后点击 Create new application context... ,会弹出一个对话框,让你创建应用上下文:
直接点 OK ,就完事了。此番动作是让 IDEA 也知道,咱在使用 SpringFramework 开发应用,IDEA 会自动识别咱写的配置,可以帮我们省很多心。
③创建容器从容器中获取对象并测试
public static void main(String[] args) {
// 1.获取StudentDaoImpl对象
//创建Spring容器,指定要读取的配置文件路径
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
//从容器中获取对象需要强制转型
StudentDao studentDao = (StudentDao) app.getBean("studentDao");
//调用对象的方法进行测试
System.out.println(studentDao.getStudentById(1));
}
解释一下这段代码的意思。读取配置文件,需要一个载体来加载它,这里选用 ClassPathXmlApplicationContext 来加载。加载完成后咱直接使用 BeanFactory 接口来接收(多态思想)。
下一步就可以从 BeanFactory 中获取 studentDao 了,由于咱在配置文件中声明了 id ,故这里就可以直接把 id 传入,BeanFactory 就可以给我们返回 Person 对象