Spring container IOC parsing and simple implementation

Source: Internet
Author: User

In recent times, "container" two words have been lingering in my ears, even eat, sleep in my mind jumping to jump. As these days of exchanges and discussions, the understanding of the container gradually deepened. In theory, things have to be implemented to practice, today, with the help of spring container implementation principle, simply say it.

To put it simply, spring is putting our beans in its container through Factory + reflection, and when we want to use a bean, we just need to call the Getbean ("Beanid") method.

The principle of simple introduction:

The principle of the spring container is actually to parse the XML file, or fetch the user-configured bean, and then put the beans into the collection by reflection, then provide a Getbean () method for us to get the beans. The following is a simple analog code:

Package com.tgb.spring.factory;  Import Java.util.HashMap;  Import java.util.List;  Import Java.util.Map;  Import org.jdom.Document;  Import org.jdom.Element;  Import Org.jdom.input.SAXBuilder;  Import Org.jdom.xpath.XPath;  public class Classpathxmlapplicationcontext implements Beanfactory {//container core, used to store injected bean private map<string,      object> container = new hashmap<string, object> ();          Parses the XML file and puts the configured bean into container by reflection Classpathxmlapplicationcontext (String fileName) throws exception{          Saxbuilder sb = new Saxbuilder ();          Document doc = Sb.build (This.getclass (). getClassLoader (). getResourceAsStream (FileName));          Element root = Doc.getrootelement ();          List List = Xpath.selectnodes (Root, "/beans/bean"); Scan for Bean in config file for (int i = 0; i < list.size (); i++) {Element bean = (Element) LIST.G             ET (i);             String id = bean.getattributevalue ("id"); String clazz = bean.geTattributevalue ("class");             Object o = Class.forName (clazz). newinstance ();            Container.put (ID, O);      }} @Override public Object Getbean (String ID) {return container.get (ID);   }  }

First declare a map that holds the bean, and then through the Jdom parse the configuration file, iterate through all the nodes and put them through reflection into the map we declared earlier. Then provide a method of Getbean (), so that we can find the bean we want through the bean ID.

The following is a simple XML configuration file:

<?xml version="1.0" encoding="UTF-8"?>  <beans>    <bean id="E" class="com.tgb.spring.factory.England" />    <bean id="S" class="com.tgb.spring.factory.Spain" />    <bean id="P" class="com.tgb.spring.factory.Portugal" />  </beans>  

The client loads the above configuration file by invoking the previous Classpathxmlapplicationcontext, and then it can get the bean we need by ID:

package com.tgb.spring.factory;  public class Test {      public static void main(String[] args) throws Exception {          //加载配置文件          BeanFactory f = new ClassPathXmlApplicationContext("applicationContext.xml");          //英格兰          Object oe = f.getBean("E");          Team e = (Team)oe;          e.say();          //西班牙          Object os = f.getBean("S");          Team s = (Team)os;          s.say();          //葡萄牙          Object op = f.getBean("P");          Team p = (Team)op;          p.say();      }  }  

Output Result:

England :我们是欧洲的中国队,不在乎这次小组没出线...  Spain   :我们是两届欧洲杯冠军、一届世界杯冠军!  Portugal:我们的C罗一个顶十个!  

Other code:

//工厂接口  package com.tgb.spring.factory;  public interface BeanFactory {      Object getBean(String id);  }  //Team接口  package com.tgb.spring.factory;  public interface Team {      void say();  }  //英格兰  package com.tgb.spring.factory;  public class England implements Team{      public void say() {          System.out.println("England:我们是欧洲的中国队,不在乎这次小组没出线...");      }  }  //西班牙  package com.tgb.spring.factory;  public class Spain implements Team{      @Override      public void say() {          System.out.println("Spain:我们是两届欧洲杯冠军、一届世界杯冠军!");      }  }  //葡萄牙  package com.tgb.spring.factory;  public class Portugal implements Team {      @Override      public void say() {          System.out.println("Portugal:我们的C罗一个顶十个!");      }  }  

Spring container IOC parsing and simple implementation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.