java spring Ioc(反射)机制

 1.java spring IOC正常写法,导入spring包

 ApplicationContext ctx = new ClassPathXmlApplicationContext("applictionContext.xml");
  Teach s = (Teach) ctx.getBean(Teachid);

ClassPathXmlApplicationContext是spring包自带,我们是不是可以自己写一个类拟的功能呢,答案是肯定的。

2.自定义ClassPathXmlApplicationContext

这里需要导入解析xml包:jdom.

2.1BeanFactory.java(先定义一个工厂接口)

package self.spring;

public interface BeanFactory {
 public Object getBean(String beanId);
}

2.2ClassPathXmlApplicationContext.java

package self.spring;

 

import java.lang.reflect.Method;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

 

import org.jdom.Element;

 

publicclass ClassPathXmlApplicationContextimplements BeanFactory{

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

 

    @Override

    public Object getBean(String beanId) {

       returnbeans.get(beanId);

    }

 

    @SuppressWarnings({"unchecked", "unused" })

    public ClassPathXmlApplicationContext(String xmlfile) {

       org.jdom.input.SAXBuilder sb =new org.jdom.input.SAXBuilder();

       org.jdom.Document doc = null;

       try {

           //构造xml文档对像

           doc = sb.build(this.getClass().getClassLoader()

                  .getResourceAsStream(xmlfile));

       } catch (Exception e) {

           System.out.println("docError:" +this.getClass() +".java\t\n "

                  + e.toString());

       }

       org.jdom.Element root = doc.getRootElement();//根元素

 

       @SuppressWarnings("rawtypes")

       List list = root.getChildren("bean");

       for (int i = 0; i < list.size(); i++) {

           org.jdom.Element element = (Element) list.get(i);

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

           if (null == id) {

              id = element.getAttributeValue("name");

           }

           String classes = element.getAttributeValue("class");

           Object o = null;

           try {

              o = Class.forName(classes).newInstance();

           } catch (Exception e) {

              System.out.println("Object oError:" +this.getClass()

                     + ".java\t\n" + e.toString());

           }

           System.out.println("id:" + id +"\t" + "classes:" + classes);

           beans.put(id, o);

           for (Element properyElement : ((List<Element>) element

                  .getChildren("property"))) {

 

              String name = properyElement.getAttributeValue("name");

              String bean = properyElement.getAttributeValue("bean");

              String value = properyElement.getAttributeValue("value");//这里暂时不写value,因为类型太多原因

              String factory_method = properyElement

                     .getAttributeValue("factory-method");//方法注入

              if (null == bean) {

                  bean = properyElement.getAttributeValue("ref");// 为了兼容spring官方属性

 

              }

 

              Object beanObject =beans.get(bean);

              String methodName ="set" + name.substring(0,1).toUpperCase()

                     + name.substring(1);

              System.out.print("method name= " + methodName);

 

              Class oo = null;

              try {

                  oo = beanObject.getClass().getInterfaces()[0];//接口

              } catch (Exception e) {

                  oo = beanObject.getClass();//

              }

              Method m = null;

              try {//小写set后面方法setmethod

                  m = o.getClass().getMethod("set" + name, oo);

              } catch (NoSuchMethodException | SecurityException er) {

              }

 

              try {//正常方法 setMethod

                  m = o.getClass().getMethod(methodName, oo);

              } catch (NoSuchMethodException | SecurityException e) {

              }

              try {

                  m.invoke(o, beanObject);//执行方法

              } catch (Exception ex) {

                  System.out.println("Error:" +this.getClass()

                         + ".java\t\n" + ex.toString());

              }

           }

       }

    }

 

}

3.测试

 

package self.service;

 

import junit.framework.TestCase;

import self.model.Teacher;

import self.spring.BeanFactory;

import self.spring.ClassPathXmlApplicationContext;

 

 

publicclass TestTeacherextends TestCase {

    publicvoid testSave(){

       BeanFactory bean =  new ClassPathXmlApplicationContext("teach_beans.xml");

       Teacher teacher=(Teacher) bean.getBean("teacher");

       teacher.setAge(30);

       teacher.setSid("No154545");

       teacher.setSname("自己写的IOC");

       TeacherService t = (TeacherService) bean.getBean("teacherService");

//     teacher.setStudent(student);

       t.saveTeacher();

    }

}

 

运行结果:

id:teacher classes:self.model.Teacher
id:tDao classes:self.impl.TeacherDAOImpl
id:teacherService classes:self.service.TeacherService
method name = setTdaomethod name = setTeach教师证号:No154545 姓名:自己写的IOC类保存成功!

4.上述要用的类及xml源

TeacherDAO.java

package self.dao;

 

import self.model.Teacher;

publicinterface TeacherDAO {

    publicvoid saveTeacher(Teacher t);

 

}

 

 

TeacherDAOImpl.java

package self.impl;

 

import self.dao.TeacherDAO;

import self.model.Teacher;

 

publicclass TeacherDAOImplimplements TeacherDAO {

    @Override

    publicvoid saveTeacher(Teacher t) {

       if(null != t){

           //数据库操作,省   

           System.out.println(t.toString()+"保存成功!");       

       }else{       

           System.out.println("Error:对像为空,不能保存!!!");

       }

    }

}

 

 

Teacher.java

package self.model;

 

publicclass Teacher {

    private Stringsid;

    private Stringsname;

    privateint age;

    public String getSid() {

       returnsid;

    }

    publicvoid setSid(String sid) {

       this.sid = sid;

    }

    public String getSname() {

       returnsname;

    }

    publicvoid setSname(String sname) {

       this.sname = sname;

    }

    publicint getAge() {

       returnage;

    }

    publicvoid setAge(int age) {

       this.age = age;

    }

    public String toString(){

       return"教师证号:"+this.getSid()+" 姓名:"+this.getSname();

      

    }

}

 

TeacherService.java

package self.service;

 

import self.dao.TeacherDAO;

import self.model.Teacher;

 

publicclass TeacherService {

    private TeacherDAOtdao;

    private Teacherteach;

    public TeacherDAO getTdao() {

       returntdao;

    }

    publicvoid setTdao(TeacherDAO tdao) {

       this.tdao = tdao;

    }

    public Teacher getTeach() {

       returnteach;

    }

    publicvoid setTeach(Teacher teach) {

       this.teach = teach;

    }

 

    publicvoid saveTeacher(){

      

       tdao.saveTeacher(teach);

    }

}

 

teach_beans.xml

<?xmlversion="1.0"encoding="UTF-8"?>

<beans>

    <beanid="teacher"class="self.model.Teacher"></bean>

    <beanid="tDao"class="self.impl.TeacherDAOImpl"></bean>

 

    <beanid="teacherService"class="self.service.TeacherService">

       <propertyname="tdao"ref="tDao"></property>

       <propertyname="teach"ref="teacher"></property>

    </bean>

</beans>

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值