Container Learning (a): hands-on simulation of spring's IOC

Source: Internet
Author: User

Introduction

It is necessary to learn the principle of the classical framework and the application of the design pattern in fact, so that we can make the object-oriented better.

This article is to simulate spring's IOC function. After the principle is clarified, it can be used better, and then provide a kind of idea for object-oriented.

Click to download the source code: Download

hands-on simulation of IOC implementations

First we put the DAO we used , Service , Entity Define it:

Student.java:

Package com.bzu.entity;    public class Student {    private int id;    private String name;    Private String address;    Set, Get method omitted  

because spring the promotion is interface-oriented programming, so we write DAO layers and Service layer is implemented in detail before we define the interface, let us implement the interface in detail. The code of the interface is very easy, which is not posted here.

Studentdaoimp.java public  class Studentdaoimp implements Studentdao {public  void Add (Student stu) {  System.out.println ("Stu is Saved");  }  }  

Studentserviceimp.java

public class Studentserviceimp implements Studentservice {  Studentdao studao=null;  Public Studentdao Getstudao () {  return studao;  }  public void Setstudao (Studentdao studao) {  This.studao = Studao;  }  @Override public  void Add (Student stu) {  studao.add (stu);  }  


      Note here that we are here to simulateSpring. Main simulationSpringin theIOCfunction. So we're going to be in the sameServicedefined in the layerDAOinstance, of course not.Newcome out and we'll go throughSpringof theIOCtake this place.DAOlayer is injected in.

Do not forget to provide a setfor DAO. Get method. Since the bottom of the IOC is actually based on the reflection mechanism, he injects the DAO in. In fact, the bottom layer comes in through reflection set .

     What we needDAOlayer,ServiceLayer also hasEntityafter the definition is done. The next step is to define our ownClasspathxmlapplicationcontextclass. Through him, in ourNewout of his object when he came to load the config file and then put ourDAOoperations are injected into ourServicelayer, inSpringin whichClasspathxmlapplicationcontextclass implements thebeanfactoryinterface, where we also define abeanfactoryinterface, in fact, this interface does not have a detailed role. We're just trying to simulateSpring.

before we define this interface and implementation class, let's take a look at what we need XML how it's written. Let's look at the configuration of the beans.xml in detail below:

Beans.xml :

<beans>  <bean id= "Studao" class= "com.bzu.dao.imp.StudentDaoImp"/>  <bean id= "Stuservice" class= "COM.BZU.SERVICE.IMP.STUDENTSERVICEIMP" >  <property name= "Studao" bean= "Studao"/>  </ Bean>  

It's all right. Configuration file We're done, next we'll take a look at our Spring Container-- How the Classpathxmlapplicationcontext is implemented in detail, Let's start by looking at his interface definition:

Beanfactory.java:

Public interface Beanfactory {public  Object Getbean (String ID);  }  

we see that the interface is actually very easy and defines a Getbean method, let's look at the detailed implementation class:

Classpathxmlapplicationcontext.java

public class Classpathxmlapplicationcontext implements beanfactory{private map<string, object> beans = new HashMap <String,Object> (); Public Classpathxmlapplicationcontext () throws exception,exception {Saxbuilder sb = new Saxbuilder (); Document doc = Sb.build (This.getclass (). getClassLoader (). getResourceAsStream ("Beans.xml")); Constructs a Document object element root = Doc.getrootelement (); Gets the root element hdlist list = Root.getchildren ("Bean");//names all the elements of the bean for (int i = 0; i < list.size (); i++) {element element = (Element) list.get (i); String id = element.getattributevalue ("id"); String clazz = Element.getattributevalue ("class"), Object o = Class.forName (clazz). newinstance (); System.out.print ("Bean ID is" + ID); System.out.println ("Clazz is" + clazz); Beans.put (ID, O); Traverse Propertyfor (Element propertyelement: (list<element>) Element.getchildren ("property")) {String name = Propertyelement.getattributevalue ("name");//Userdaostring Bean = propertyelement.getattributevalue ("Bean");// UobjecT beanobject = Beans.get (bean);//Userdaoimpl instance//constructor setter method String methodName = "Set" + name.substring (0,1). Touppe Rcase () + name.substring (1); System.out.println ("Setter Method name =" +methodname); Method m = O.getclass (). GetMethod (Methodname,beanobject.getclass (). getinterfaces () [0]); M.invoke (o, beanobject);} }} @Overridepublic Object Getbean (String ID) {return beans.get (ID);}}

      First we define a container map <string, object> beans bean that we parse from the configuration file. why use map in the configuration file. bean id

We put this ID into the map key , and then value is loaded with our detailed The bean object.

     after this container, let's look at the following .Classpathxmlapplicationcontextthe construction method of this method is that weSpringmanaging the core of the container,The first half of this construction method is usedJdomanalytic way, putXMLinside theBeanparse it out. And then we'll parse it out.Beanput it in ourBeanin the container.

The latter part is mainly to parse the configuration fileBeanAt the same time to check out thisBeanis there any need for injections inBean, assuming there are words. He went through the inside. Propertyproperty to get his shot.Beanname. And then construct aSetmethod, and then through reflection, call injectionBeanof theSetmethod, so that what we needBeanwas injected into it.

Finally, let's take a look at the implementation of the interface Getbean , in fact, this method is very easy. is to put the corresponding bean from within the bean container, based on the ID of the provided bean. Take it out.

it's all right. Everything we need is well defined. Let's take a look at the following to see if the spring we're imitating will be able to inject us with the DAO layer we need.

public static void Main (string[] args) throws Exception {  Classpathxmlapplicationcontext context = new Classpathxmlap Plicationcontext ();  Student stu = new Student ();  Studentservice service = (studentservice) context.getbean ("Stuservice");  Service.add (stu);  }  

Executes the code. Console output:

Bean Idis Studao, Clazz is COM.BZU.DAO.IMP.STUDENTDAOIMP

Bean Idis Stuservice, Clazz is COM.BZU.SERVICE.IMP.STUDENTSERVICEIMP

Settermethod name = Setstudao

Stu Issaved

Summary

good. Successfully injected into this, we have to imitate the spring Ioc to this end, and finally through a graphical way to summarize The advantages of the Ioc

General code. Without the help of IoC. The relationship between classes and classes should be this


Studentserviceimp need to rely on studentdaoimp. Such dependencies are determined when the program is not executed.

with the Spring container. With IoC, the relationship between classes and classes should be this


Studentserviceimp no longer dependent Studentdaoimp , but through Spring The way in which services are provided, Studentserviceimp and Studentdaoimp are linked together, and such dependencies are determined when the program executes.

Studentserviceimp was independent. Independence means simplicity and flexibility. So the idea of the IoC delay Injection is an indispensable tool in object-oriented development.

Container Learning (a): hands-on simulation of spring's IOC

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.