A simple implementation of the Spring IOC (demo included)

Source: Internet
Author: User


to put it simply, Spring is through the factory + reflection will be our Bean into its container, when we want to use a Bean , you only need to call the Getbean ("Beanid") Method can be .

The principle of simple explanation:

Spring the principle of the container, in fact, is through the analysis XML files, create what we need through reflection. Bean , again put these Bean put it in the collection, and then provide an external Getbean () method so that we get the Bean .

let's simply implement a Demo

Beans.xml

<?xml version= "1.0" encoding= "UTF-8"?><beans>      <bean id= "user" class= "Com.yyb.model.User"/>      <bean id= "Userdao" class= "Com.yyb.dao.impl.UserDAOImpl"/>      <bean id= "UserService" class= " Com.yyb.service.UserService ">          <property name=" Userdao "bean=" Userdao "/>      </bean>  

Beanfactory

Public interface Beanfactory {Object Getbean (String name);  }

Classpathxmlapplicationcontext: Reads XML file contents and creates object and object relationships (using setter mode)

Package Com.yyb.spring;import Java.io.ioexception;import Java.lang.reflect.invocationtargetexception;import Java.lang.reflect.method;import Java.util.hashmap;import Java.util.list;import Java.util.Map;import Org.jdom.document;import Org.jdom.element;import Org.jdom.jdomexception;import Org.jdom.input.SAXBuilder;public Class Classpathxmlapplicationcontext implements Beanfactory{private map<string, object> beans = new hashmap< String, object> ();p ublic Classpathxmlapplicationcontext () throws Jdomexception, IOException, Instantiationexception, Illegalaccessexception,classnotfoundexception, SecurityException, NoSuchMethodException, IllegalArgumentException, Invocationtargetexception{saxbuilder sb = new Saxbuilder ();//Construct Document Object doc = Sb.build ( ClassPathXmlApplicationContext.class.getClassLoader (). getResourceAsStream ("Beans.xml"));//Get root elements element root =  Doc.getrootelement ();//take to the root element all elements List List = Root.getchildren (); for (int i = 0; i < list.size (); i++) {Element element = (Element) list.get (i);//Take ID child element String beanid = Element.getattributevalue ("id");//Take class child element string CLZSS = Element.getattributevalue ("class");//Instantiate object o = Class.forName (CLZSS). newinstance ();//Put all the beans in the map beans.put ( Beanid, O);//Get property to make dependency injection for (Element propertyelement: (list<element>) Element.getchildren ("property")) { String name = Propertyelement.getattributevalue ("name"); SYSTEM.OUT.PRINTLN (name);//userdaostring bean = Propertyelement.getattributevalue ("Bean"); System.out.println (bean);//userdao//the object from the Beans.xml to the class by id//object beanobj = this.getbean (name);// Object beanobj = This.getbean (bean) from Beans.xml, based on the ID of the class; System.out.println (beanobj);//[email protected]//forms Setxxx Method name string methodName = "Set" + name.substring (0, 1). toUpperCase () + name.substring (1); System.out.println (name.substring (0, 1). toUpperCase ());//usystem.out.println (name.substring (1));// SerDAOSystem.out.println (methodName);//setuserdao//reflection mechanism invokes the method, injecting the object into the context of the environment when the bean is loaded, method M = O.getclass (). GetMethod (MEthodname,beanobj.getclass (). getinterfaces () [0]); System.out.println (O.getclass ());//class com.yyb.service.UserServiceSystem.out.println (Beanobj.getclass (). Getinterfaces () [0]);//interface com.yyb.dao.UserDAOSystem.out.println (m);//public void Com.yyb.service.UserService.setUserDAO (Com.yyb.dao.UserDAO)//performs an injection, equivalent to executing a setxxx (args..) Method M.invoke (O, beanobj);}}} @Overridepublic Object Getbean (String name) {return beans.get (name);}}

The effect of this code is:

Service service= (Service) beans.get ("UserService");

dao dao = (dao) beans.get ("Userdao");

// Dependency Injection, Service Implementing Dependencies DAO the implementation

Service.setdao (DAO);

User: Entity class

public class User {    private String userName;      private String password;      /**      * @return The UserName *      * * Public      String getusername ()      {          return userName;      }      /**      * @param userName      * The            userName to set */public      void Setusername (String userName)      {          this.username = userName;      }      /**      * @return The password *      * * Public      String GetPassword ()      {          return password;      }      /**      * @param password      * The  password to set */public      void SetPassword (String password)      {          This.password = password;      }      Public String toString ()      {          StringBuffer sb = new StringBuffer ();          Sb.append (this.username);          Sb.append (This.password);          return sb.tostring ();      }  }

Userdao

public interface Userdao {void Save (User u);   void Delete (); }

Userdaoimpl

public class Userdaoimpl implements Userdao {@Override public      void Save (User u) {          System.out.println ("User:" + u). ToString ());      }      @Override public      Void Delete () {          System.out.println ("delete User");                }  }

UserService

public class UserService {   private Userdao Userdao;     public void AddUser (User u)      {          this.userDAO.save (U);      }      /**      * @return The Userdao *      *      /Public Userdao Getuserdao ()      {          return userdao;      }      /**      * @param userdao      * The            Userdao to set */public      void Setuserdao (Userdao Userdao)      { C19/>this.userdao = Userdao;      }  }

Let's briefly test the effect of the implementation:


Client

public class Client {public static void main (string[] args) throws Instantiationexception, Illegalaccessexception, CLASSN Otfoundexception, SecurityException, Nosuchmethodexception, IllegalArgumentException, InvocationTargetException, Jdomexception, IOException {beanfactory factory = new Classpathxmlapplicationcontext ();//direct access via factory        UserService UserService = (userservice) factory.getbean ("UserService");         In fact, user can also obtain user        u= (user) Factory.getbean ("user") from the factory;        User U = new user ();          U.setusername ("Yyb");          U.setpassword ("1234");          Userservice.adduser (U);//print result yyb1234}}


Of course above we are through Setter method Injection, you can also use the constructor injection, which is the establishment of the relationship when the object is created (that is, the UserService constructor to add a function to the Userdao the assignment Operation )

Summarize:

above through A brief implementation example of the IOC simulates the implementation of the IOC in spring, although only a small part of the dependency injection is done in spring, but it shows the application of the Java Reflection mechanism in spring, which allows us to better understand the implementation of the IOC in principle. can also provide a solution for us to implement our own Spring framework .


Spring IOC Implementation Principle DEMO:IOC




Spring IOC Simple Implementation (with demo)

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.