spring的IOC
1.spring环境搭建和入门
1.导入依赖:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
2.在resource下面创建bean.xml配置文件,bean.xml添加约束(找到spring的首页,点击core-->搜索xmlns,复制约束到bean.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
3.把对象的创建给spring来管理 (在bean.xml配置id和class)
<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"></bean>
<bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl"></bean>
4.获取IOC的核心容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//根据id获取bean对象,两种方式获取
IAccountService as = (IAccountService) ac.getBean("accountService");
IAccountDao adao = ac.getBean("accountDao",IAccountDao.class);
2.Spring 的IOC创建对象的解析
1.获取bean对象ApplicationContext:
ApplicationContext的三个常用的实现类:
ClassPathXmlApplicationContext:它可以加载类路径下的配置文件,要求配置文件必须在类路径下,不在的话,加载不了.
FileSystemXmlApplicationContext:它可以加载磁盘任意路径下的配置文件(必须有访问权限)
AnnotationConfigApplicationContext:它是用于读取注解来创建容器的。
2.核心容器的两个接口引发的问题:
ApplicationContext:(单例对象)
它在构建核心容器时,创建对象采取的策略是立即加载的方式。也就是只要一读取完配置文件马上创建配置文件对象。
BeanFactory:(多例对象)
它在构建核心容器时,创建对象采取的策略是延迟加载的方式。也就是什么时候根据id获取对象,什么时候才真正创建对象。
3.

浙公网安备 33010602011771号