`
vvggsky
  • 浏览: 65442 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

自己编写IOC

    博客分类:
  • J2SE
阅读更多
<?xml version="1.0" encoding="UTF-8"?>   
<mybeans >   
<bean id="first" name="first" implement="com.my.ioc.testpackage.MybeanOneImpl"></bean>   
</mybeans> 


public class XmlToBean {    
   
    public Mybean getBean() throws Exception {    
        Mapping map = new Mapping();    
        URL u = this.getClass().getClassLoader().getResource("com/my/ioc/config/config-mapping.xml");    
        map.loadMapping(u);    
        Unmarshaller un = new Unmarshaller(Mybean.class);    
        File file = new File("myconfig.xml");    
        file.getAbsoluteFile();    
        Reader reader = new FileReader(file);    
        // Unmarshaller unmarshaller = new Unmarshaller(map);    
        un.setMapping(map);    
        Mybean read = (Mybean) un.unmarshal(reader);    
   
        return read;    
    }    
}   



<?xml version="1.0" encoding="UTF-8"?>   
<!DOCTYPE mapping PUBLIC "-//EXOLAB/Castor Mapping DTD Version 1.0//EN"    
    "http://castor.org/mapping.dtd">   
<mapping>   
    <class name="com.my.ioc.config.Mybean" auto-complete="true">   
        <map-to xml="my_beans" />   
        <field name="mybeans" type="com.my.ioc.config.ConfigBean" collection="arraylist">   
            <bind-xml name="bean" node="element" />   
        </field>   
    </class>   
    <class name="com.my.ioc.config.ConfigBean" auto-complete="true">   
        <field name="id">   
            <bind-xml name="id"  node="attribute"/>   
        </field>   
        <field name="name">   
            <bind-xml name="name" node="attribute"/>   
        </field>   
        <field name="implement">   
            <bind-xml name="implement"  node="attribute"/>   
        </field>   
    </class>   
</mapping>   



public class ConfigBean implements Serializable{    
    private String id;    
   
    private String name;    
   
    private String implement;    
   
    public String getId() {    
        return id;    
    }    
   
    public void setId(String id) {    
        this.id = id;    
    }    
   
    public String getImplement() {    
        return implement;    
    }    
   
    public void setImplement(String implement) {    
        this.implement = implement;    
    }    
   
    public String getName() {    
        return name;    
    }    
   
    public void setName(String name) {    
        this.name = name;    
    }    
}    
   
public class Mybean {    
   
    private List<ConfigBean> mybeans;    
   
    public List<ConfigBean> getMybeans() {    
        return mybeans;    
    }    
   
    public void setMybeans(List<ConfigBean> mybeans) {    
        this.mybeans = mybeans;    
    }    
   
}   


@Retention(RetentionPolicy.RUNTIME)    
@Target(ElementType.TYPE)    
public @interface MyClassAnnotation {    
    String isInvoke() default "NO";    
} 

@Retention(RetentionPolicy.RUNTIME)    
public @interface MyMethodAnnotation {    
    String isTransaction() default "NO";    
}


class MyTranstionHandler implements MyHandler,InvocationHandler{    
    private Object o;    
   
    private MyJotmTranstion tra;    
   
    public MyTranstionHandler(Object delegate) {    
        o = delegate;    
//        tra = new MyJotmTranstion();    
    }    
   
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {    
        Object a = null;    
        try {    
   
            if (method.isAnnotationPresent(MyMethodAnnotation.class)) {    
                MyMethodAnnotation an = method.getAnnotation(MyMethodAnnotation.class);    
                if (an.isTransaction().equals("yes") && an != null) {    
//                    getTransactionManager().begin();    
                    System.out.print("\n" + "start");    
                    a = method.invoke(o, args);    
//                    getTransactionManager().commit();    
                    System.out.print("\n" + "end");    
                } else {    
                    a = method.invoke(o, args);    
                }    
            }    
            return null;    
        } catch (Exception e) {    
            System.out.print("\n" + "invoke Exception");    
        }    
        return a;    
    }    
        
    private TransactionManager getTransactionManager()    
    {    
        return tra.getTransactionManager();    
    }    
}    

4 现在给出一个具体的实现类

java 代码
@MyClassAnnotation(isInvoke="yes")    
public class MybeanOneImpl implements IMybeanOne {    
    @MyMethodAnnotation(isTransaction = "yes")    
    public void printString() {    
        System.out.print("\n"+" don some thing");    
    }    
    @MyMethodAnnotation(isTransaction = "yes")    
    public void printString1() {    
        System.out.print("\n"+" good work");    
    }    
}   

 

5 然后给出我的bean工厂了

java 代码
public class MyBeanFactory {    
    private static MyBeanFactory instance = null;    
   
    private MyBeanFactory() {    
        try {    
            initBean();    
        } catch (Exception e) {    
            int b = 0;    
        }    
    }    
   
    public static MyBeanFactory getInstance() {    
        return instance = new MyBeanFactory();    
    }    
   
    private Map<String, Class> beanMap = new HashMap<String, Class>();    
   
    private Object getConfigBean() throws Exception {    
        XmlToBean xml = new XmlToBean();    
        return xml.getBean();    
    }    
   
    private void initBean() throws Exception {    
        Mybean beans = (Mybean) getConfigBean();    
        List<ConfigBean> configList = beans.getMybeans();    
        for (int i = 0; i < configList.size(); i++) {    
            ConfigBean bean = configList.get(i);    
            registerBean(bean.getName(), bean.getImplement());    
   
        }    
        int i = 0;    
    }    
   
    private void registerBean(String beanName, String className) throws Exception {    
        Class bean = Class.forName(className);    
        beanMap.put(beanName, bean);    
   
    }    
   
    public Object getRegistedBean(String beanName) throws Exception {    
   
        Class o = beanMap.get(beanName);    
       if(o.isAnnotationPresent(MyClassAnnotation.class))    
           return o.newInstance();    
        MyClassAnnotation classAnn = (MyClassAnnotation) o.getAnnotation(MyClassAnnotation.class);    
        if (classAnn.isInvoke().equals("yes")) {    
            InvocationHandler handler = new MyTranstionHandler(o.newInstance());    
            return   Proxy.newProxyInstance(o.getClassLoader(), o.getInterfaces(), handler);    
        } else {    
            return o.newInstance();    
        }    
    }    
}   

 

6 测试代码

 

java 代码
public static void main(String[] args) {    
       MyBeanFactory f = MyBeanFactory.getInstance();    
       try {    
           IMybeanOne o =(IMybeanOne) f.getRegistedBean("first");    
           o.printString();    
       } catch (Exception e) {    
           System.out.print("error "+e.getMessage());    
       }    
   }   






String idValue = map.get("id");   
if (idValue == null) {   
  throw ...;   
}   
int id = Integer.parseInt(idValue);   
  
String name = map.get("name");   
if (name == null) {   
  name = "";   
}   
  
String sexValue = map.get("sex");   
if (sexValue == null) {   
  throw ...;   
}   
Gender sex = Gender.valueOf(sexValue);   
...  

String idValue = map.get("id");
if (idValue == null) {
  throw ...;
}
int id = Integer.parseInt(idValue);

String name = map.get("name");
if (name == null) {
  name = "";
}

String sexValue = map.get("sex");
if (sexValue == null) {
  throw ...;
}
Gender sex = Gender.valueOf(sexValue);
...



public final class PropertyConverter<T> {   
  private final Class<T> targetType;   
     
  private PropertyConverter(Class<T> targetType) {...}   
  
  public static <T> PropertyConverter<T> to(Class<T> targetType) {   
    return new PropertyConverter<T>(targetType);   
  }   
  
  public T from(final Map<String, String> map) {   
    return Proxy.newProxyInstance(   
      new Class[]{targetType}, targetType.getClassLoader(), new InvocationHandler() {   
        public Object invoke(Object proxy, Method method, Object[] args) {   
          String value = map.get(method.getName());   
          if (value == null) {   
            Object defaultValue = method.getDefaultValue();   
            if (defaultValue == null) {   
              throw ...;   
            }   
            return defaultValue;   
          }   
          return convert(value, method.getReturnType());   
        }   
    });   
  }   
}  

public final class PropertyConverter<T> {
  private final Class<T> targetType;
  
  private PropertyConverter(Class<T> targetType) {...}

  public static <T> PropertyConverter<T> to(Class<T> targetType) {
    return new PropertyConverter<T>(targetType);
  }

  public T from(final Map<String, String> map) {
    return Proxy.newProxyInstance(
      new Class[]{targetType}, targetType.getClassLoader(), new InvocationHandler() {
        public Object invoke(Object proxy, Method method, Object[] args) {
          String value = map.get(method.getName());
          if (value == null) {
            Object defaultValue = method.getDefaultValue();
            if (defaultValue == null) {
              throw ...;
            }
            return defaultValue;
          }
          return convert(value, method.getReturnType());
        }
    });
  }
}


convert()函数是调用apache的ConvertUtilsBean做的,没什么说的。 

@interface Foo {   
  int id();   
  String name() default "";   
  Gender sex();   
}   
  
Map<String, String> map = ...;   
Foo foo = PropertyConverter.to(Foo.class).from(map);   
foo.id();   
foo.name(); 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics