单手写Spring系列 (1) Base BeanFactory

 模拟bean工厂基础版

 

  实体类

  bean标记类

  工厂类

  测试类

 

 

1、需要组装的实体

package com.myspring.beans;

public class Teacher {
       private String tname;
      
       

	public String getTname() {
		return tname;
	}

	public void setTname(String tname) {
		this.tname = tname;
	}
       
}

 

2、bean标记、 相当于xml 

public class BeanDefined {
	
	private String beanId;
	private String classPath;
	public String getBeanId() {
		return beanId;
	}
	public void setBeanId(String beanId) {
		this.beanId = beanId;
	}
	public String getClassPath() {
		return classPath;
	}
	public void setClassPath(String classPath) {
		this.classPath = classPath;
	}
	
	

}

 

 

3、bean工厂:

import java.util.List;

public class BeanFactory {
	
	   private List<BeanDefined> beanDefinedList;

	public List<BeanDefined> getBeanDefinedList() {
		return beanDefinedList;
	}

	public void setBeanDefinedList(List<BeanDefined> beanDefinedList) {
		this.beanDefinedList = beanDefinedList;
	}
	
	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;
	}
	   

}

 

 

4、测试程序

public class TestMain {

	public static void main(String[] args) throws Exception {
		
		  //1.声明注册bean
		  BeanDefined beanObj = new BeanDefined();
		  beanObj.setBeanId("teacher");
		  beanObj.setClassPath("com.myspring.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);

	}

}

 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值