Spring technology Insider: Spring IoC principles

Source: Internet
Author: User

Spring technology Insider: Spring IoC principles

Some time ago I read the chapter on IOC principles in Spring technology, and I felt that there were too many codes and I was not familiar with them. I specially collected some information about IOC principles, I have a deep impression on how IOC works.
The idea of IOC is that Spring containers can create and coordinate these mutually dependent objects. The object only needs the relational business logic.
The SpringIOC container is executed as follows:
1. Resource PositioningThat is, you must first find the applicationContext. xml file
2. BeanDefinition LoadingTo load the data in the XML file to BeanDefinition for later processing.
3. Inject BeanDefinition data into the IOC container
4. Inject the data in BeanDefinition into dependencies
IoC dynamically provides other objects required by an object during system running. This is achieved through DI (Dependency Injection, Dependency Injection. For example, object A needs to operate the database. In the past, we always had to write code in A to obtain A Connection object. With spring, we only need to tell spring that A Connection is required in, as for how to construct the Connection and when to construct it, A does not need to know. When the system is running, spring will create A Connection at an appropriate time and inject it into A like an injection. This completes the control of the relationship between objects. A needs to rely on the Connection to run normally, and the Connection is injected into A by spring, so the dependency injection name is like this. How is DI implemented? A major feature after Java 1.3 is reflection, which allows programs to dynamically generate objects, execute object methods, and change object attributes during runtime, spring is injected through reflection.
For example, there are many intermediary companies in real life, such as I love my family. I love my family and there will be a variety of housing materials. When we look for a house, we only need to tell me the house we need, and I love my family will provide us with a suitable house according to our needs. In this way, we don't have to go to the Internet, community advertisements, and other places to collect suitable houses. The whole process is controlled by my intermediary, now, let's see if this intermediary makes the entire process simple and pleasant. Of course, in our real life, we need to pay the intermediary fee. For example, SpringIOC also needs to maintain the ApplicationContext configuration file, which is a cost. In the face of Spring, we can ignore the cost. Haha.
Let me take a look at the SpringIOC running process:
1. First load ApplicationContext. xml to locate the resource.
First, the resource is located in the AbstractBeanDefinitionReader class under Springframe.LoaderBeanDefinitions(String location,Set actualResources) Line 98, the following example:

public static void main(String[] args) {        ApplicationContext context = new FileSystemXmlApplicationContext(                "applicationContext.xml");        User user= (User) context.getBean("user");        user.write();    }
 
          
    
   
  
 public class User{    private String name;    public void write() {        System.out.println("my name is:"+name);    }    public void setName(String name) {        this.name = name;    }}

The running program will output: my name is jader. Obviously, SpringIOC has injected the value in the property into the name attribute of the User.
Next we will analyze how Spring is implemented.
2. BeanDefinition Loading
Loading and parsing are ultimately implemented by the refresh () method of the AbstractApplicationContext class under Springframework. This method is critical and contains resource loading and parsing, including additional lazy-init processing, line 445, the following example:
First, we define a Bean to store the attributes of the Bean.

  /* Bean Id */    private String id;    /* Bean Class */    private String type;    /* Bean Property */    private Map
  
    properties = new HashMap
   
    ();
   
  

Next, Spring starts to load our configuration file and stores the configuration information in a HashMap. The key of HashMap is the Bean Id, and the value of HasMap is the Bean, only in this way can we use context. the getBean ("user") method obtains the Animal class. We all know that Spirng can inject basic types, and can inject types such as List and Map. Next, let's take Map as an example to see how Spring is saved.

   
          
   
                    
                         
      
       jader
                      
                     
                         
      
       26
                      
             
       
  

3. Register BeanDefinition with the IOC container
The registration is implemented in the registerBeanDefinition (String beanName, BeanDefinition beanDefinition) method under the DefaultListableBeanFactory class of Spring frame. line 664 is implemented. The following example shows:

            if (beanProperty.element("map") != null) {                    Map
  
    propertiesMap = new HashMap
   
    ();                    Element propertiesListMap = (Element) beanProperty                            .elements().get(0);                    Iterator
     propertiesIterator = propertiesListMap                            .elements().iterator();                    while (propertiesIterator.hasNext()) {                        Element vet = (Element) propertiesIterator.next();                        if (vet.getName().equals("entry")) {                            String key = vet.attributeValue("key");                            Iterator
     valuesIterator = vet.elements()                                    .iterator();                            while (valuesIterator.hasNext()) {                                Element value = (Element) valuesIterator.next();                                if (value.getName().equals("value")) {                                    propertiesMap.put(key, value.getText());                                }                                if (value.getName().equals("ref")) {                                    propertiesMap.put(key, new String[] { value                                            .attributeValue("bean") });                                }                            }                        }                    }                    bean.getProperties().put(name, propertiesMap);                }
   
  

4. Dependency Injection
SpringIOC's final dependency injection is implemented through the doCreateBean (finale String beanName, final RootBeanDefinition mbd, final Object [] args) method (line 480) of AbstractAutowireCapableBeanFactory, the key methods in this method include populateBean () and createBeanInstance (). The implementation of injection is achieved through the setPropertyValue () method of BeanWrapperImpl extends AbstractPropertyAccessor class to implement line 911.
The principle is: implemented through the reflection mechanism. when instantiating a class, it injects class attributes saved in HashMap into the class through the set Method in the reflection call class.

public static Object newInstance(String className) {        Class
   cls = null;        Object obj = null;        try {            cls = Class.forName(className);            obj = cls.newInstance();        } catch (ClassNotFoundException e) {            throw new RuntimeException(e);        } catch (InstantiationException e) {            throw new RuntimeException(e);        } catch (IllegalAccessException e) {            throw new RuntimeException(e);        }        return obj;    }
public static void setProperty(Object obj, String name, String value) {        Class
   clazz = obj.getClass();        try {            String methodName = returnSetMthodName(name);            Method[] ms = clazz.getMethods();            for (Method m : ms) {                if (m.getName().equals(methodName)) {                    if (m.getParameterTypes().length == 1) {                        Class
   clazzParameterType = m.getParameterTypes()[0];                        setFieldValue(clazzParameterType.getName(), value, m,                                obj);                        break;                    }                }            }        } catch (SecurityException e) {            throw new RuntimeException(e);        } catch (IllegalArgumentException e) {            throw new RuntimeException(e);        } catch (IllegalAccessException e) {            throw new RuntimeException(e);        } catch (InvocationTargetException e) {            throw new RuntimeException(e);        }}

Finally, it returns the instance of this class to us and we can use it. Let's take Map as an example to see how it works. The code I wrote creates a HashMap and injects the HashMap into the class to be injected.

          if (value instanceof Map) {                Iterator
   entryIterator = ((Map
  ) value).entrySet()                        .iterator();                Map
  
    map = new HashMap
   
    ();                while (entryIterator.hasNext()) {                    Entry
     entryMap = (Entry
    ) entryIterator.next();                    if (entryMap.getValue() instanceof String[]) {                        map.put((String) entryMap.getKey(),                                getBean(((String[]) entryMap.getValue())[0]));                    }                }                BeanProcesser.setProperty(obj, property, map);            }
   
  

The specific implementation of each step above is marked with the class name, method name, and number of lines. You can view the Spring source code on your own, which is not shown here.
It is difficult to understand the SpringIOC principle in the first chapter of Spring technology. This article can help us understand it. I have read a book for hundreds of times and its meaning is self-evident. I can read this article repeatedly when you do not understand it, we hope we can make common progress.

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.