【spring】bean的声明与创建实例

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做成一个代理返回

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值