剖析Spring管理Bean的原理(学习笔记)

/**
* 模拟spring的解析bean.xml的类
* @author river
*
*/
public class RiverClassPathXMLApplicationContext
{
private List<BeanDefinition> beanDefinitions = new ArrayList<BeanDefinition>();

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

public RiverClassPathXMLApplicationContext(String filename)
{
this.readXML(filename);
this.instanceBeans();
}

/**
* 完成实例化
*/
private void instanceBeans()
{
for (BeanDefinition beanDefinition : beanDefinitions)
{
if (beanDefinition.getClassName() != null
&& !"".equals(beanDefinition.getClassName().trim()))
{
try
{
sigletons.put(beanDefinition.getId(), Class.forName(
beanDefinition.getClassName()).newInstance());
} catch (Exception e)
{
e.printStackTrace();
}
}
}

}

public Object getBean(String beanName)
{
return this.sigletons.get(beanName);
}

/**
* 读取配置文件,filename为bean的配置文件
*
* @param filename
*/
private void readXML(String filename)
{
SAXReader saxReader = new SAXReader();
Document document = null;
try
{
URL xmlpath = this.getClass().getClassLoader()
.getResource(filename);
document = saxReader.read(xmlpath);
Map<String, String> nsMap = new HashMap<String, String>();
nsMap.put("ns", "http://www.springframework.org/schema/beans");// 假如命名空间
XPath xsub = document.createXPath("//ns:beans/ns:bean");// 创建beans/bean
xsub.setNamespaceURIs(nsMap);// 设置命名空间
List<Element> beans = xsub.selectNodes(document);// 获取文档下的bean
for (Element element : beans)
{
String id = element.attributeValue("id");// 获取id属性
String clazz = element.attributeValue("class");// 获取class属性
BeanDefinition beanDefine = new BeanDefinition(id, clazz);
beanDefinitions.add(beanDefine);
}
} catch (Exception e)
{
e.printStackTrace();
}
}
}

PersonService 类的一个实现类:

public class PersonServiceBean implements PersonService {

/* (non-Javadoc)
* @see com.river.spring.PwesionService#save()
*/
public void save()
{
System.out.println("save ()");
}
}

bean.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-2.5.xsd">
      <bean id="personService" class="com.river.service.impl.PersonServiceBean"/>
</beans>

测试:

/**
* personService为bean中的id
*/
public void instanceSpring()
{
RiverClassPathXMLApplicationContext ctx = new RiverClassPathXMLApplicationContext("beans.xml");
PersonService ps = (PersonService) ctx.getBean("personService");
ps.save();
}

结果:save();

你可能感兴趣的:(spring,bean,xml,配置管理)