浅析使用Setter方法的注入bean的机制

首先按照spring使用属性注入其他的bean配置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"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<bean id="personDao" class="com.heying.dao.impl.PersonDaoBean"></bean>  
<bean id="personService" class="com.heying.service.PersonServiceBean">
    <property name="personDao" ref="personDao"></property>
</bean>
</beans>

配置属性的实体对象:
XmlBeanDefinition.java
String id: bean的id名称
String name:bean的class名称
List ddefinitions:存放property 属性值

package com.heying.service;

import java.util.ArrayList;
import java.util.List;

public class XmlBeanDefinition {

    private String id;
    private String name;
    private List<PropertyDdefinition> ddefinitions = new ArrayList<PropertyDdefinition>();


    public XmlBeanDefinition(String id, String name) {
        this.id = id;
        this.name = name;
    }

    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    public List<PropertyDdefinition> getDdefinitions() {
        return ddefinitions;
    }

    public void setDdefinitions(List<PropertyDdefinition> ddefinitions) {
        this.ddefinitions = ddefinitions;
    }
}

PropertyDdefinition.java
String name:property 的name属性
String ref:property 的ref属性

package com.heying.service;

public class PropertyDdefinition {

    private String name;
    private String ref;

    public PropertyDdefinition(String name, String ref) {
        this.name = name;
        this.ref = ref;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getRef() {
        return ref;
    }
    public void setRef(String ref) {
        this.ref = ref;
    }
}

MyClassPathXmlApplicationContext.java

package com.heying.test;

import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.XPath;
import org.dom4j.io.SAXReader;

import com.heying.service.PropertyDdefinition;
import com.heying.service.XmlBeanDefinition;

public class MyClassPathXmlApplicationContext {
    private List<XmlBeanDefinition> beanDefinitions = new ArrayList<XmlBeanDefinition>();
    private Map<Object, Object> sigletons = new HashMap<Object, Object>();

    public MyClassPathXmlApplicationContext(String fileName) {
        this.readXmlFile(fileName);
        this.instanceBeans();
        this.injectObject();
    }

    /**
     * 依赖注入
     */
private void injectObject() {
    for ( XmlBeanDefinition beanDefinition : beanDefinitions) {
        Object bean = sigletons.get(beanDefinition.getId());
        if(bean != null){
            try {
                PropertyDescriptor[] propers = Introspector.getBeanInfo(bean.getClass()).getPropertyDescriptors();

                for (PropertyDdefinition propertyDdefinition : beanDefinition.getDdefinitions()) {
                        for (PropertyDescriptor propertyDescriptor : propers) {
                            if(propertyDdefinition.getName().equals(propertyDescriptor.getName())){  // 判断是否相等
                                Method setter = propertyDescriptor.getWriteMethod(); // 获取set方法
                                if(setter != null){
                                    Object value = sigletons.get(propertyDdefinition.getRef());
                                    setter.setAccessible(true);
                                    setter.invoke(bean,value); // 引入对象到属性
                                }
                                break;
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

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

    /**
     * 读取XML信息
     * @param fileName
     */
    @SuppressWarnings("unchecked")
    private void readXmlFile(String fileName) {
        SAXReader saxReader = new SAXReader();
        Document document = null;

        try {
            URL xmlPath = this.getClass().getClassLoader().getResource(fileName); // 获取相对路径
            document = saxReader.read(xmlPath); // 读取xml文件

            Map<String, String> nsMap = new HashMap<String, String>();
            nsMap.put("ns", "http://www.springframework.org/schema/beans"); // 加入命名空间
            XPath xPath = document.createXPath("//ns:beans/ns:bean"); // 创建查询路径
            xPath.setNamespaceURIs(nsMap); // 设置命名空间

            List<Element> beans = xPath.selectNodes(document); // 获取所有节点
            for (Element element : beans) {
                String id = element.attributeValue("id");
                String clazz = element.attributeValue("class");
                XmlBeanDefinition xmlBeanDefinition = new XmlBeanDefinition(id, clazz);

                XPath propertysub = document.createXPath("ns:property");
                propertysub.setNamespaceURIs(nsMap); // 设置空间

                List<Element> propertys = propertysub.selectNodes(element);
                for (Element property : propertys) {
                    String propertyName = property.attributeValue("name");
                    String propertyRef = property.attributeValue("ref");
                    System.out.println("[propertyName="+propertyName+",propertyRef="+propertyRef+"]");
                    PropertyDdefinition ddefinition = new PropertyDdefinition(propertyName, propertyRef);
                    xmlBeanDefinition.getDdefinitions().add(ddefinition);
                }
                beanDefinitions.add(xmlBeanDefinition);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取bean实例
     * @param beanName
     * @return
     */
    public Object getBean(String beanName){
        return this.sigletons.get(beanName);
    }
}

serviceBean:

public class PersonServiceBean implements PersonService{
    private PersonDao personDao; 
    public void save() {
        personDao.add(); // 通过依赖注入使得对象由外部容器创建并管理
    }
    public PersonDao getPersonDao() {
        return personDao;
    }

    public void setPersonDao(PersonDao personDao) {
        this.personDao = personDao;
    }
}

main:

main{
    MyClassPathXmlApplicationContext applicationContext = new MyClassPathXmlApplicationContext("beans.xml");
    PersonService personService = (PersonService) applicationContext.getBean("personService");
    personService.save();
}

这里写图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值