IOC的概念和作用
1、采用new创建对象:
2、使用工厂模式创建对象
IOC:控制反转,把创建对象的权利交给框架,是框架的重要特征,并非面向对象编程的专用术语,它包括依赖注入和依赖查找
明确IOC的作用:削减计算机程序的耦合(解除我们代码中的依赖关系),使用spring的IOC解决程序耦合。
Spring基于XML的IOC环境搭建
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">
<!--把对象的创建交给spring管理-->
<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"></bean>
<bean id="accountDao" class="com.itheima.dao.impl.AccountDaoImpl"></bean>
</beans>
获取Spring的ioc核心容器,并根据id获取对象
public class Client {
/**
* 获取spring的ioc核心容器,并根据id获取对象
* @param args
*/
public static void main(String[] args) {
//1.获取核心容器对象
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
//2.根据id获取bean对象
IAccountService as = (IAccountService) applicationContext.getBean("accountService");
IAccountDao adao = applicationContext.getBean("accountDao",IAccountDao.class);
System.out.println(applicationContext);
System.out.println(as);
System.out.println(adao);
}
}
输出:
ApplicationContext的三个常用实现类
ClassPathXmlApplicationContext:它可以加载类路径下的配置文件,要求配置文件必须在类路径在,不在的话,加载不了
FileSystemXmlApplicationContext:它可以加载磁盘任意路径下配置文件(必须有访问权限)
AnnotationConfigApplicationContext:它是用于读取注解创建容器的。
核心容器的两个接口引发的问题
ApplicationContext:它在构建核心容器时,创建对象采用的是立即加载的方式,也就是说,只要一读取完配置文件马上就创建配置文件中配置的对象。单例对象适用。实例开发中更多的是采用此接口创建对象。
BeanFactory:它在构建核心容器时,创建对象采用的是延迟加载的方式,也就是说,什么时候根据id获取对象了,什么时候才真正创建对象。多例对象适用。