工厂模式的配置文件和BeanFactory类:
例子:
accountService=com.itheima.service.iml.AccountServiceIml
accountDao=com.itheima.dao.AccountDaoImpl
package com.itheima.factory;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
* ClassName:BeanFactory
* Package:com.itheima.factory
* Description:
*
* @Date:2019/10/27 20:31
* @Author:liangshuai@shuaige.com
*/
public class BeanFactory {
private static Properties props;
//定义一个Map,用于存放我们要创建的对象,我们把它称之为容器
private static Map<String,Object> beans;
static {
try {
props = new Properties();
InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
props.load(in);
beans=new HashMap<String, Object>();
//取出配置文件中所有的key
Enumeration keys = props.keys();
//遍历枚举
while (keys.hasMoreElements()){
String key=keys.nextElement().toString();
String beanPath= props.getProperty(key);
Object value=Class.forName(beanPath).newInstance();
//把key和value存入容器中
beans.put(key,value);
}
}catch (Exception e){
throw new ExceptionInInitializerError("初始化properties失败!");
}
}
public static Object getBean(String beanName){
return beans.get(beanName);
}
/*public static Object getBean(String beanName){
Object bean=null;
try {
String beanPath=props.getProperty(beanName);
bean=Class.forName(beanPath).newInstance();
}catch (Exception e){
e.printStackTrace();
}
return bean;
}*/
}
IOC 配置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">
<bean id="accountService(相当于key)" class="全限定类名"></bean>
</beans>
ApplicationContext的三个实现类:
1.ClassPathXmlApplicationContext:它可以加载类路径下的配置文件,要求配置文件必须在类路径下,不在的话,加载不了。
2.FileSystemXmlApplicationContext:它可以加载磁盘任意路径下的配置文件(必须有访问权限)
3.AnnotationConfigApplicationContext:它是用于读取注解创建容器的。
核心容器的两个接口引发出的问题:
ApplicationContext: 它在构建核心容器时,创建对象采取的策略是采用立即加载的方式。也就是说,只要一读取完配置文件马上就创建配置文件中配置的对象。 单例对象适用
BeanFactory:它在构建核心容器时,创建对象采取的策略是采用延迟加载的方式。也就是说,什么时候根据id获取对象了,什 么时候才真正的创建对象。 多例对象适用