您的位置:首页 > 编程语言 > Java开发

Spring框架源码学习---DI的实现

2015-07-12 23:02 525 查看
依赖注入:

this.readXML(filename);

List<BeanDefinition> beanDefines = new ArrayList<BeanDefinition>();

BeanDefinition中有PropertyDefinition

this.instanceBeans();

先实例化每个Bean,但并不注入值,通过反射实现的。然后以id为键存入singleton Map中。

this.injectObject();

遍历所有的bean,从上面map中得到bean实例,然后通过内省看看这个bean实例有哪些属性需要注入,如果有的话,再将其和beanDefines中的比较,从singleton中取出,然后通过内省的方式调用setter方法注入即可。

public class ItcastClassPathXMLApplicationContext {

private List<BeanDefinition> beanDefines = new ArrayList<BeanDefinition>();

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

public ItcastClassPathXMLApplicationContext(String filename){

this.readXML(filename);

this.instanceBeans();

this.injectObject();//注入对象

}

/**

* 为bean对象属性注入值

*/

private void injectObject() {

for(BeanDefinition beanDefinition:beanDefines){//循环所有的bean

Object bean=sigletons.get(beanDefinition.getId());//通过Id取得实例化后beanDefines中的Bean

if(bean!=null){//判断bean是否获取到

try {

PropertyDescriptor[] ps=Introspector.getBeanInfo(bean.getClass()).getPropertyDescriptors();// 取得bean的属性描述

for(PropertyDefinition propertyDefinition:beanDefinition.getPropertys()){

for(PropertyDescriptor properdesc:ps){

if(propertyDefinition.getName().equals(properdesc.getName())){//判断循环的属性是否在bean中存在

Method setter=properdesc.getWriteMethod();//获取属性的setter方法

if(setter!=null){//判断属性是否有setter方法

Object value=sigletons.get(propertyDefinition.getRef());//取得ref所引用的对象

setter.setAccessible(true);//设置为允许访问,防止setter方法为私有时抛出异常

setter.invoke(bean, value);//把引用对象注入到属性中

}

break;

}

}

}

} catch (Exception e) {

e.printStackTrace();

}

}

}

}

/**

* 完成bean的实例化

*/

private void instanceBeans() {

for(BeanDefinition beanDefinition : beanDefines){

try {

if(beanDefinition.getClassName()!=null && !"".equals(beanDefinition.getClassName().trim()))

sigletons.put(beanDefinition.getId(), Class.forName(beanDefinition.getClassName()).newInstance());

} catch (Exception e) {

e.printStackTrace();

}

}

}

/**

* 读取xml配置文件

* @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);//读取文件的内容得到一个document

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);

XPath propertysub=element.createXPath("ns:property");//通过element创建查询路径,此时的路径为相对路径(即://ns:beans/ns:bean下的ns:property)

propertysub.setNamespaceURIs(nsMap);//设置命名空间

List<Element> propertys=propertysub.selectNodes(element);//获取文档下所有bean节点

for(Element property:propertys){

String propertyName=property.attributeValue("name");//获取属性的name和ref

String propertyref=property.attributeValue("ref");

// System.out.println(propertyName+"="+propertyref);

PropertyDefinition propertyDefinition=new PropertyDefinition(propertyName,propertyref);//将name和ref赋给propertyDefinition

beanDefine.getPropertys().add(propertyDefinition);

}

beanDefines.add(beanDefine);

}

}catch(Exception e){

e.printStackTrace();

}

}

/**

* 获取bean实例

* @param beanName

* @return

*/

public Object getBean(String beanName){

return this.sigletons.get(beanName);

}

}

--------------------------------------------------------------------------------------------------

<?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="personDao" class="cn.itcast.dao.impl.PersonDaoBean"></bean>

<bean id="personService" class="cn.itcast.service.impl.PersonServiceBean">

<property name="personDao" ref="personDao"></property>

<property name="name" value="itcast"></property>

<property name="id" value="88"></property>

</bean>

</beans>

-----------------------------------------------------------------------------------------------------------------

public class PersonServiceBean implements PersonService {

private PersonDao personDao;

private String name;

private int id;

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public PersonDao getPersonDao() {

return personDao;

}

public void setPersonDao(PersonDao personDao) {

this.personDao = personDao;

}

@Override

public void save(){

System.out.println("id="+id+"\tname="+name);

personDao.add();

}

}

-----------------------------------------------------------

public class ItcastClassPathXMLApplicationContext {

private List<BeanDefinition> beanDefines = new ArrayList<BeanDefinition>();

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

public ItcastClassPathXMLApplicationContext(String filename) {

this.readXML(filename);

this.instanceBeans();

this.injectObject();// 注入对象

}

/**

* 为bean对象属性注入值

*/

private void injectObject() {

for (BeanDefinition beanDefinition : beanDefines) {// 循环所有的bean

Object bean = sigletons.get(beanDefinition.getId());// 通过Id取得实例化后beanDefines中的Bean

if (bean != null) {// 判断bean是否获取到

try {

PropertyDescriptor[] ps = Introspector.getBeanInfo(bean.getClass()).getPropertyDescriptors();// 取得bean的属性描述

for (PropertyDefinition propertyDefinition : beanDefinition.getPropertys()) {

for (PropertyDescriptor properdesc : ps) {

if (propertyDefinition.getName().equals(properdesc.getName())) {// 判断循环的属性是否在bean中存在

Method setter = properdesc.getWriteMethod();// 获取属性的setter方法

if (setter != null) {// 判断属性是否有setter方法

Object value = null;

if(propertyDefinition.getRef()!=null && !"".equals(propertyDefinition.getRef().trim())){// 如果引用存在

value = sigletons.get(propertyDefinition.getRef());// 取得ref所引用的对象

} else {

// 通过ConvertUtils将propertyDefinition.getValue()转换成与properdesc.getPropertyType()对应的值

value = ConvertUtils.convert(propertyDefinition.getValue(), properdesc.getPropertyType());

}

setter.setAccessible(true);// 设置为允许访问,防止setter方法为私有时抛出异常

setter.invoke(bean, value);// 把引用对象注入到属性中

}

break;

}

}

}

} catch (Exception e) {

e.printStackTrace();

}

}

}

}

/**

* 完成bean的实例化

*/

private void instanceBeans() {

for (BeanDefinition beanDefinition : beanDefines) {

try {

if (beanDefinition.getClassName() != null&& !"".equals(beanDefinition.getClassName().trim()))

sigletons.put(beanDefinition.getId(),Class.forName(beanDefinition.getClassName()).newInstance());

} catch (Exception e) {

e.printStackTrace();

}

}

}

/**

* 读取xml配置文件

*

* @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);// 读取文件的内容得到一个document

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);

XPath propertysub = element.createXPath("ns:property");// 通过element创建查询路径,此时的路径为相对路径(即://ns:beans/ns:bean下的ns:property)

propertysub.setNamespaceURIs(nsMap);// 设置命名空间

List<Element> propertys = propertysub.selectNodes(element);// 获取文档下所有bean节点

for (Element property : propertys) {

String propertyName = property.attributeValue("name");// 获取属性的name和ref

String propertyref = property.attributeValue("ref");

String propertyValue = property.attributeValue("value");

// System.out.println(propertyName+"="+propertyref);

PropertyDefinition propertyDefinition = new PropertyDefinition(propertyName, propertyref, propertyValue);// 将name和ref赋给propertyDefinition

beanDefine.getPropertys().add(propertyDefinition);

}

beanDefines.add(beanDefine);

}

} catch (Exception e) {

e.printStackTrace();

}

}

参考:http://www.cnblogs.com/mingforyou/archive/2011/12/20/2294925.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: