javaSE 模拟Spring框架的Ioc

来源:互联网 发布:讲文明知礼仪手抄报 编辑:程序博客网 时间:2024/05/22 12:15
Spring框架的Ioc模拟实现
Spring框架一直与我当年研究道家的无为的思想贴近,14年的最爱,曾经迷死 Rod Johnson了, Spring的缔造者, 拥有着计算机与音乐的双重天赋。唉...好羡慕ing吐舌头 个人理解:Ioc作为更高层次的解耦,运用到的javaSE技术, XML解析和java反射。 真的设计的很好很好,给我10年也想不出来这种方式。 例子如下:
首先创建一个xml文件 用于仿照spring配置文件application.xml 
YanD.xml
<?xml version="1.0" encoding="UTF-8"?><beans> <bean id="person" class="Test.Person">   <property name="name" value="YanD"/> </bean></beans>
声明一个属性name 并设值为YanD 
在Test包下新建一个Person类 Person.java
package Test;public class Person { public String name;public Person(){}  public Person(String name){this.name = name;}public void setName(String name) {this.name = name;} public String getName() {return name;}public void writeCode(){ //敲代码方法 System.out.println(this.name+"在敲代码");} }
创建ioc工具类 YanDIocUtils.java, 这边的解析xml用的是dom解析方式
package Test;import java.io.File;import java.lang.reflect.Method;import javax.xml.parsers.DocumentBuilderFactory;import org.w3c.dom.Document;import org.w3c.dom.Element;import org.w3c.dom.NodeList;public class YanDIocUtils {  //解析xml的document类  private Document document;  // 配置文件的位置  private String configPath;    //初始化类   public YanDIocUtils(String configPath)  { try{   document = DocumentBuilderFactory.newInstance().newDocumentBuilder()         .parse(new File("src/<span style="color: rgb(51, 51, 51); font-family: SimSun; line-height: 39.1px;">YanD.xml</span>")); }catch(Exception e) { e.printStackTrace(); }   }  //模拟spring 的 getBean方法  public Object getBean(String beanId) throws Exception  {  Object obj = null;  NodeList nodeList = document.getElementsByTagName("bean");  //找寻 目标beanId   int index = -1;  for(int i = 0; i < nodeList.getLength(); i ++)  {  Element element = (Element)nodeList.item(i);  //判断beanId   String beanIdStr = element.getAttribute("id");  if(beanId.equals(beanIdStr))  {  index = i;  break;  }  }  //找到该beanId  if(index != -1)  {Element ele = (Element)nodeList.item(index);String classPath = ele.getAttribute("class"); //类的路径Element ele2 = (Element)ele.getElementsByTagName("property").item(0);    String attribName = ele2.getAttribute("name");//属性名称    String attribValue = ele2.getAttribute("value");//注入的值//根绝类的路径反射得到类    Class classzs = Class.forName(classPath);    obj = classzs.newInstance();//通过反射实例化Object//通过obj获取原类中的set方法名进行设值    Method method = classzs.getMethod("set"+attribName.substring(0,1).toUpperCase()+attribName.substring(1), String.class);    method.invoke(obj, attribValue);  }        return obj;  }}
编写测试类进行测试 
package Test;import spring.YanDIocUtils;public class TestIoc {public static void main(String[] args) {try{YanDIocUtils yanDIoc = new YanDIocUtils("src/YanD.xml");Person person = (Person)yanDIoc.getBean("person");person.sayHello();}catch(Exception e){e.printStackTrace();}} }
运行该程序, 控制台上上就会出现YanD在敲代码字样
这样创建Person的实例就交给YanDIocUtils.java来完成了, 当然和spring框架的ApplicationContxt类比起来自然差了很远. 
比如多个属性值的配置我这里就没有实现, 虽然实现起来也不难. 
 






1 0