感谢ITCAST发布的免费视频。

package junit.test;

 

import java.lang.annotation.ElementType;

import java.lang.annotation.Retention;

import java.lang.annotation.RetentionPolicy;

import java.lang.annotation.Target;

 

@Retention(RetentionPolicy.RUNTIME)

@Target({ElementType.FIELD, ElementType.METHOD})

public @interface MyResource {

    public String name() default "";

}

 

package junit.test;

 

import java.beans.IntrospectionException;

import java.beans.Introspector;

import java.beans.PropertyDescriptor;

import java.lang.reflect.Field;

import java.lang.reflect.InvocationTargetException;

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.apache.commons.beanutils.ConvertUtils;

import org.dom4j.Document;

import org.dom4j.Element;

import org.dom4j.XPath;

import org.dom4j.io.SAXReader;

 

public class MyClassPathXMLApplicationContext {

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

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

   

    public MyClassPathXMLApplicationContext(String fileName) {

       this.readXML(fileName);

       this.instanceBeans();

       this.annotationInject();

       this.injectObject();

    }

 

    private void annotationInject() {

       // TODO Auto-generated method stub

       for (String beanName : sigletons.keySet()) {

           Object bean = sigletons.get(beanName);

          

           if (bean != null) {

              try {

                  PropertyDescriptor[] ps = Introspector.getBeanInfo(bean.getClass()).getPropertyDescriptors();

             

                  for (PropertyDescriptor properdesc : ps) {

                     Method setter = properdesc.getWriteMethod();

                 

                     if (setter != null && setter.isAnnotationPresent(MyResource.class)) {

                         MyResource resource = setter.getAnnotation(MyResource.class);

                         Object value = null;

                        

                         if (resource.name() != null && !resource.name().equals("")) {

                            String name = resource.name();

                            value = sigletons.get(name);

                         } else {

                            value = sigletons.get(properdesc.getName());

                           

                            if (value == null) {

                                for (String key : sigletons.keySet()) {

                                   if (properdesc.getPropertyType().isAssignableFrom(sigletons.get(key).getClass())) {

                                       value = sigletons.get(key);

                                       break;

                                   }

                                }

                            }

                         }

                        

                         setter.setAccessible(true);

                         setter.invoke(bean, value);

                     }

                  }

                 

                  Field[] fields = bean.getClass().getDeclaredFields();

                 

                  for (Field field : fields) {

                     if (field.isAnnotationPresent(MyResource.class)) {

                         MyResource resource = field.getAnnotation(MyResource.class);

                         Object value = null;

                        

                         if (resource.name() != null && !resource.name().equals("")) {

                            String name = resource.name();

                            value = sigletons.get(name);

                         } else {

                            value = sigletons.get(field.getName());

                           

                            if (value == null) {

                                for (String key : sigletons.keySet()) {

                                   if (field.getType().isAssignableFrom(sigletons.get(key).getClass())) {

                                       value = sigletons.get(key);

                                       break;

                                   }

                                }

                            }

                         }

                        

                         field.setAccessible(true);

                         field.set(bean, value);

                     }

                  }

              } catch (IntrospectionException e) {

                  // TODO Auto-generated catch block

                  e.printStackTrace();

              } catch (IllegalArgumentException e) {

                  // TODO Auto-generated catch block

                  e.printStackTrace();

              } catch (IllegalAccessException e) {

                  // TODO Auto-generated catch block

                  e.printStackTrace();

              } catch (InvocationTargetException e) {

                  // TODO Auto-generated catch block

                  e.printStackTrace();

              }

           }

       }

    }

 

    private void injectObject() {

       // TODO Auto-generated method stub

       for (BeanDefinition beanDefinition : beanDefines) {

           Object bean = sigletons.get(beanDefinition.getId());

          

           if (bean != null) {

              try {

                  PropertyDescriptor[] ps = Introspector.getBeanInfo(bean.getClass()).getPropertyDescriptors();

                 

                  for (PropertyDefinition properties : beanDefinition.getProperties()) {

                     for (PropertyDescriptor properDesc : ps) {

                         if (properties.getName().equals(properDesc.getName())) {

                            Method setter = properDesc.getWriteMethod(); //get the setter method

                            if (setter != null) {

                                Object value = null;

                               

                                if (properties.getRef() != null && !properties.getRef().equals("")) {

                                   value = sigletons.get(properties.getRef());                              

                                } else {

                                   value = ConvertUtils.convert(properties.getValue(), properDesc.getPropertyType());

                                }

                               

                                setter.setAccessible(true);

                                setter.invoke(bean, value); //set ref object to the property   

                            }

                           

                            break;

                         }

                     }

                  }

              } catch (Exception e) {

                  // TODO Auto-generated catch block

                  e.printStackTrace();

              }

             

 

           }

       }

       //List<PropertyDefinition> properties =

    }

 

    private void instanceBeans() {

       // TODO Auto-generated method stub

       for (BeanDefinition beanDefinition : beanDefines) {

           try {

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

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

              }

           } catch (Exception e) {

              e.printStackTrace();

           }         

       }

    }

 

    private void readXML(String fileName) {

       // TODO Auto-generated method stub

       SAXReader saxReader = new SAXReader();

       Document document = null;

      

       try {

           URL xmlpath = this.getClass().getClassLoader().getResource(fileName);

           Map<String, String> nsMap = new HashMap<String, String>();

           XPath xsub = null;

           List<Element> beans = null;

          

           document = saxReader.read(xmlpath);

           nsMap.put("ns", "http://www.springframework.org/schema/beans"); //add namespace

           xsub = document.createXPath("//ns:beans/ns:bean"); //create beans/bean query path

           xsub.setNamespaceURIs(nsMap); //set namespace

           beans = xsub.selectNodes(document); //get nodes of the document

          

           for (Element element : beans) {

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

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

              BeanDefinition beanDefine = new BeanDefinition(id, clazz);        

              XPath propertySub = element.createXPath("ns:property");

              List<Element> properties = null;

             

              propertySub.setNamespaceURIs(nsMap);

              properties = propertySub.selectNodes(element);

             

              for (Element property : properties) {

                  String propertyName = property.attributeValue("name");

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

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

                  PropertyDefinition pro = new PropertyDefinition();

                 

                  pro.setName(propertyName);

                  pro.setRef(propertyRef);

                  pro.setValue(propertyValue);

                 

                  beanDefine.getProperties().add(pro);

              }

             

              beanDefines.add(beanDefine);

           }

       } catch (Exception e) {

           e.printStackTrace();

       }

    }

   

    public Object getBean(String beanName) {

       return this.sigletons.get(beanName);

    }

}

posted on 2009-02-04 21:08  IT Person  阅读(1104)  评论(0编辑  收藏  举报