Analog implementation of IoC container

Keywords: Java xml Spring Attribute

The core of Spring's IoC is inversion of control, which hands over the operation controller to implement the object, which is managed by the IoC container, and obtains configuration information from the configuration file. Java provides perfect support for XML documents, and dom4j has powerful functions. Next, I use JDOM as an open source project, which can be used to analyze, generate and serialize XML documents with pure Java technology Simulate the implementation of IoC container.

1. Complete the project in the traditional way.
1. Define interface

package com.decipher.car;

public interface Car {
    public String getBrand();
    public void run();
    
}


2. Next, implement the Car interface

package com.decipher.carImplementation;
import com.decipher.car.Car;
public class BMWCar implements Car{
    private String MyBrand="BMW";
    public String getBrand(){
        return MyBrand;
    }
    public void run(){
        System.out.println(MyBrand+" is runing");
    }
}


3. Create a new Human class

package com.decipher.human;
import com.decipher.car.Car;
public class Human {
    private Car car;

    public Car getCar() {
        return car;
    }

    public void setCar(Car car) {
        this.car = car;
    }
    public void myCarRun(){
        car.run();
    }
}


4. Write the test class finally

package com.decipher.humen;

import com.decipher.car.Car;
import com.decipher.carImplementation.BMWCar;
import com.decipher.human.Human;

public class HumenTest {
    public static void main(String[] args) throws Exception {
        Human human=new Human();
        Car car=new BMWCar();
        human.setCar(car);
        human.myCarRun();    
    }
}

 


5. The operation results are shown in the figure:



II. JDOM simulation IoC container inversion control
Import the jdom.jar package into the project project directory before programming.
1. Create a new BeanFactory

package com.decipher.spring;

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

 


2. Implement BeanFactory interface

package com.decipher.spring;

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.input.SAXBuilder;

public class ClassPathXmlApplicationContext {
    //Store key value pairs of each instance
    private Map<String,Object> beans=new HashMap<String,Object>();
    //Construction method
    public ClassPathXmlApplicationContext() throws Exception{
        //read XML File
        SAXBuilder sb=new SAXBuilder();
        //Construct document object DOC
        Document doc=sb.build(this.getClass().getClassLoader().getResource("beans.xml"));
        //Obtain XML Document root element
        Element root=doc.getRootElement();
        //Get all child elements under the root element
        List list=root.getChildren("bean");
        //Traverse all Bean element
        for(int i=0;i<list.size();i++){
            //Obtain the first i individual Bean element
            Element element=(Element)list.get(i);
            //Get the first i individual Bean Elemental id Property and store it in a string variable id in
            String id=element.getAttributeValue("id");
            //Get the first i individual Bean Elemental class Property and store it in a string variable clazz in
            String clazz=element.getAttributeValue("class");
            //Using reflection to generate class objects is equivalent to generating class objects, which are stored in the Map in
            Object o=Class.forName(clazz).newInstance();
            System.out.println(id);
            System.out.println(clazz);
            beans.put(id,o);//take id And object o Deposit in Map in
            //Right. i individual bean Each under element property Traversal of child elements
            for(Element propertyElement:(List<Element>)element.getChildren("property")){
                //Obtain property Elemental name Attribute value
                String name=propertyElement.getAttributeValue("name");
                //Obtain property Elemental bean Attribute value
                String beanInstance=propertyElement.getAttributeValue("bean");
                //Get an instance of the injected object
                Object beanObject=beans.get(beanInstance);
                //Obtain setter Method name of method,Form is setXxx
                String methodName="set"+name.substring(0, 1).toUpperCase()+name.substring(1);
                System.out.println("method name= "+methodName);
                //Use reflection to get the specified name, and specify the setXxx Method
                Method m=o.getClass().getMethod(methodName, beanObject.getClass().getInterfaces()[0]);
                //Calling object o Of setXxx Method
                m.invoke(o,beanObject);
            }
        }
    }
        public Object getBean(String id){
            return beans.get(id);
        }
}

 


3. Configure beans.xml file

<beans>
    <bean id="baomacar" class="com.decipher.carImplementation.BMWCar">
    </bean>
    <bean id="human" class="com.decipher.human.Human">
        <property name="car" bean="baomacar"></property>
    </bean>
</beans>

 


4. Write test class HumenTest

package com.decipher.humen;

import com.decipher.spring.ClassPathXmlApplicationContext;
import com.decipher.car.Car;
import com.decipher.carImplementation.BMWCar;
import com.decipher.human.Human;

public class HumenTest {
    public static void main(String[] args) throws Exception {    
        ClassPathXmlApplicationContext ctx=new ClassPathXmlApplicationContext();
        Human human=(Human)ctx.getBean("human");
        human.myCarRun();
    }
}

 


5. Operation is as shown in the figure:

6. summary
As can be seen from the above two instantiation objects, in the traditional way, the programmer manages the class objects, while in the simulated IOC container, the controller that operates on the class objects is handed over to the IOC container, and the ApplicationContext in the IOC container processes the XML configuration file. For each configured bean in the XML document, that is, it is stored in the Map, and the programmer does not need another new object, but directly It can be obtained from the container, and the inversion of control can loosen the coupling and hand over the control right.

Posted by jinwu on Sat, 16 Nov 2019 07:03:35 -0800