千山鸟飞绝 万径人踪灭
勤练内功,不断实践招数。争取早日成为武林高手
依赖注入的方式:
第一、通过接口注入
第二、通过构造函数注入,设置对象参数
第三、通过setter方法注入。
后两者运用居多。


通过内部bean注入,其缺点是内部bean只能被一个外部bean使用
如下:
<bean id="personService"
  class="cn.itcast.service.impl.PersonServiceBean">
  <property name="IPersonDao">
         <bean class="cn.itcast.dao.impl.PersonDaoBean"></bean><!--   内部bean注入 -->
  </property>
  
  </bean>
  也可以换为:通过 ref的方式也是可以的,其优点是通过ref参数,可以被多个bean引用。

<bean id="personService"
  class="cn.itcast.service.impl.PersonServiceBean">
  <property name="IPersonDao" ref="personDaoBean"></property>
  
  </bean>
  <bean id="personDaoBean" class="cn.itcast.dao.impl.PersonDaoBean"></bean>  


剖析依赖注入的内部机制:通过基本数据类型的向属性值类型的转换



/**
 * 实现的spring容器
 *
 * @author Administrator
 *
 */
public class ItcastClassPathXMLApplicationContext {

 private List<BeanDefinition> beanDefines = new ArrayList<BeanDefinition>();
 private Map<String, Object> sigletons = new HashMap<String, Object>();

 public ItcastClassPathXMLApplicationContext() {

 }

 public ItcastClassPathXMLApplicationContext(String filename) {
  // System.out.println("构造方法 ");
  this.readXml(filename);// 调用 读取配置文件 的方法
  this.instanceBeans();// 调用bean的实例化
  this.injectObject();// 注入对象
 }

 /**
  * 为bean对象的属性注入值
  */
 private void injectObject() {
  for (BeanDefinition beanDefinition : beanDefines) {
   Object bean = sigletons.get(beanDefinition.getId());
   if (bean != null) {
    // 取得属性描述 ,是一个数组
    try {
     PropertyDescriptor[] ps = Introspector.getBeanInfo(
       bean.getClass()).getPropertyDescriptors();
     for (PropertyDefinition propertyDefinition : beanDefinition
       .getPropertys()) {// 取所有属性
      for (PropertyDescriptor properdesc : ps) {
       if (propertyDefinition.getName().equals(
         properdesc.getName())) {
        Method setter = properdesc.getWriteMethod();// 获取属性的setter方法.
        // private
        if (setter != null) {
         Object value=null;
         if(propertyDefinition.getRef()!=null && !"".equals(propertyDefinition.getRef().trim())){
          value = sigletons
            .get(propertyDefinition
              .getRef());
          
         }else{
          //将配置文件里字符串类型转换为属性类型的值
          value=ConvertUtils.convert(propertyDefinition.getValue(), properdesc.getPropertyType());
          
         }
         setter.setAccessible(true);// 设置为可访问
         setter.invoke(bean, value);// 把引用对象注入到属性
         
        }
        break;
       }
      }
     }
    } catch (Exception e) {
     e.printStackTrace();
    }

   }
  }

 }

 /**
  * 完成bean的实例化
  */
 private void instanceBeans() {
  // System.out.println("bean实例化方法被调用");
  // 利用反射机制把bean实例化
  for (BeanDefinition beanDefinition : beanDefines) {
   try {
    // 判断BeanDefinition的实例获得的类名不为null和空串
    if (beanDefinition.getClassName() != null
      && !"".equals(beanDefinition.getClassName().trim()))
     sigletons.put(beanDefinition.getId(), Class.forName(
       beanDefinition.getClassName()).newInstance());
   } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }

  }

 }

 /**
  * 读取配置文件信息
  *
  * @param filename
  */
 private void readXml(String filename) {
  // System.out.println("读取xml文件的方法被调用了");

  SAXReader saxReader = new SAXReader();// 创建读取器
  Document document = null;
  try {
   URL xmlpath = this.getClass().getClassLoader()
     .getResource(filename);//取得当前xml文件在本地的位置
   
   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);
    XPath propertysub = element.createXPath("ns:property");// 船舰查询路径

    propertysub.setNamespaceURIs(nsMap);// 设置命名空间
    List<Element> propertys = propertysub.selectNodes(element);// 查找节点
    for (Element property : propertys) {
     String propertyName = property.attributeValue("name");// 取得property的name值
     String propertyref = property.attributeValue("ref");// 取得property的ref值
     String propertyValue = property.attributeValue("value");// 取得property的value值

     PropertyDefinition propertyDefinition = new PropertyDefinition(
       propertyName, propertyref,propertyValue);
     beanDefine.getPropertys().add(propertyDefinition);// 将属性对象加入到bean中
    }

    beanDefines.add(beanDefine);
   }
  } catch (Exception e) {
   e.printStackTrace();

  }

 }

 /**
  * 获取bean 实例
  *
  * @param beanName
  * @return
  */
 public Object getBean(String beanName) {

  
  return this.sigletons.get(beanName);
 }

}


  

<bean id="personService"
  class="cn.itcast.service.impl.PersonServiceBean">
  <property name="IPersonDao" ref="personDaoBean"></property>
  
  <property name="name" value="Itcast"></property>
  <property name="age" value="15"></property>
  </bean>
  <bean id="personDaoBean" class="cn.itcast.dao.impl.PersonDaoBean"></bean>  
  


public class SpringTest {

 @BeforeClass
 public static void setUpBeforeClass() throws Exception {

 }
 @Test
 public void instanceSpring() {
//  ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(
//    "beans.xml");
  ItcastClassPathXMLApplicationContext ctx=new ItcastClassPathXMLApplicationContext("beans.xml");
//  
  IPersonService ipersonService = (IPersonService)ctx
    .getBean("personService");
  ipersonService.Save();
 // ctx.close();
  // ctx.registerShutdownHook();

 }
}


public class PropertyDefinition {
 private String name;
 private String ref;
 private String value;
 public PropertyDefinition(String name, String ref,String value) {
  
  this.name = name;
  this.ref = ref;
  this.value=value;
 }
 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;
}
其他略。

out:
Itcast
15
这是personDaoBean的Add()方法

posted on 2009-08-27 15:03 笑口常开、财源滚滚来! 阅读(226) 评论(0)  编辑  收藏 所属分类: spring学习

只有注册用户登录后才能发表评论。


网站导航: