spring工厂
默认使用构造方法来创建bean
实际得到的实例,是容器返回类的代理(aop监控)
简单流程:声明注册bean,声明spring工厂,向spring工厂索要实例对象
// 模拟spring工厂获取实例对象
//1.声明注册bean
BeanDefined beanObj = new BeanDefined();
beanObj.setBeanId("teacher");
beanObj.setClassPath("com.kaikeba.beans.Teacher");
List beanList = new ArrayList();
beanList.add(beanObj);//spring核心配置
//2.声明一个Spring提供BeanFacotory
BeanFactory factory = new BeanFactory();
factory.setBeanDefinedList(beanList);
//3.开发人员向BeanFactory索要实例对象.
Teacher t= (Teacher) factory.getBean("teacher");
System.out.println(t);
public class BeanDefined{
private String beanId;
private String classPath;
// set get
}
public class BeanFactory{
private List<BeanDefined> beanDefinedList;
// get set
public Object getBean(String beanId) throws Exception{
Object instance;
for(BeanDefined beanObj:beanDefinedList){
if(beanId.equals(beanObj.getBeanId())){
String classPath = beanObj.getClassPath();
Class classFile= Class.forName(classPath);
//在默认情况下,Spring工厂是通过调用当前类默认工作方法创建实例对象
instance= classFile.newInstance();
return instance;
}
}
return null;
}
}
// 单例多例实例创建,单例存放在hashmap中,多例直接反射创建
单例 VS 多例
spring默认的实例创建模式是singleton
scope=“singleton” ,这样类会在Spring容器启动时,被创建被保存在Spring框架SingletonList。在每次用户调用getBean方法索要时,此时只会返回同一个实例对象
scope=“prototype”,这样类不会在Spring容器启动时在每次用户调用getBean方法索要时,此时返回全新实例对象
BeanPostProcessor
理解:将bean做成一个代理返回