模仿spring的IOC容器

 

package app;

 

import java.io.InputStream;

import java.lang.reflect.InvocationTargetException;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

 

import org.apache.commons.beanutils.PropertyUtils;

import org.dom4j.Document;

import org.dom4j.Element;

import org.dom4j.io.SAXReader;

 

public class ApplicationContext {

private Map<String, BeanDefinition> beans=new HashMap<String, BeanDefinition>();

/**

* 初始化beanMap

* @param string

* @throws Exception 

*/

public ApplicationContext(String config) throws Exception {

//1.读取config对应的xml文件,把读取到的所有的bean节点封装为对应的beanDefinition,并将其放入beans中

init(config);

//2.创建对应的bean实例,并且把bean实例放入beanMap中

initBean();

//3.为由property节点的bean的属性赋值

initBeanProperties();

}

/**

* 初始化bean的实例

* @throws Exception 

* @throws InvocationTargetException 

* @throws IllegalAccessException 

*/

private void initBeanProperties() throws Exception {

for(BeanDefinition bd:beans.values()){

List<PropertyDefinition> pds=bd.getPropertyDefinition();

if(pds.size()>0){

for(PropertyDefinition pd:pds){

String propertyName=pd.getName();

String ref=pd.getRef();

Object propertyValue=beanMap.get(ref);

PropertyUtils.setProperty(beanMap.get(bd.getId()), propertyName, propertyValue);

}

}

}

}

/**

* 创建bean实例

* @throws Exception 

* @throws IllegalAccessException 

* @throws InstantiationException 

*/

private void initBean() throws Exception {

for(BeanDefinition bd:beans.values()){

String clazz=bd.getClazz();

String id=bd.getId();

Object obj=Class.forName(clazz).newInstance();

beanMap.put(id, obj);

}

}

/**

* 读取配置文件

* @param config

* @throws Exception

*/

private void init(String config) throws Exception {

SAXReader reader=new SAXReader();

InputStream is=getClass().getClassLoader().getResourceAsStream(config);

Document doc=reader.read(is);

Element root=doc.getRootElement();

List<Element> eles=root.elements("bean");

for(Element ele:eles){

String id=ele.attributeValue("id");

String clazz=ele.attributeValue("class");

BeanDefinition bd=new BeanDefinition(id, clazz);

beans.put(id, bd);

List<Element> props=ele.elements("property");

for(Element prop:props){

String name=prop.attributeValue("name");

String ref=prop.attributeValue("ref");

PropertyDefinition pd=new PropertyDefinition(name, ref);

bd.getPropertyDefinition().add(pd);

}

}

}

private Map<String, Object> beanMap=new HashMap<String, Object>();

/**

* 根据传入的beanName,从beanMap中获取对应的Bean对象

* @param beanName

* @return

*/

public Object getBean(String beanName){

return beanMap.get(beanName);

}

}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值