The study of the IOC container of Spring Technology Insider reading notes

Source: Internet
Author: User

First article: Concept and Design principles

Implementation of the IOC container as one of the core elements of spring it's very necessary to take a look at

1. Concept

The IoC (inversion of control, inversion of controls) must consider the question: what aspects of control are reversed?

For this question, Martin Flower concludes that the acquisition of dependent objects is reversed. Based on this, he created a better name for control reversal: Dependency Injection.

SPRINGIOC module is an implementation of this idea, the IOC container to create and find dependent object control to the container, the container is injected into the combined object, reduce the coupling between components, facilitate the reuse of functions, easy to test.

2. The design idea and realization of IOC container

The SPRINGIOC container design has two main container series:

① implements the simple container series of the Beanfactory interface, which implements the most basic functions of the container.

②applicationcontext application context, as the highest form of the container exists, in the implementation of simple containers based on the addition of many framework-oriented features, the application environment has been a lot of adaptation.

The design of the IOC container in spring can be consulted:

650) this.width=650; "src=" Https://s4.51cto.com/wyfs02/M01/9D/96/wKioL1mCiiWCoti6AADalKnBPGU403.jpg "title=" IOC container interface Design "width=" "height=" 516 "border=" 0 "hspace=" 0 "vspace=" 0 "style=" width:800px;height:516px; "alt=" Wkiol1mciiwcoti6aadalknbpgu403.jpg "/>

These two types of containers are then analyzed in detail to see how they are designed and implemented.

First, Beanfactory.

As an IOC container at the bottom of spring, Beanfactory has only the most basic functions for bean management.

Definition of Beanfactory:

 &  for public interface beanfactory {    // Differentiate through containers to get beanfactory generated objects and get Factorybean itself   StringFACTORY_BEAN_PREFIX =  "&";   //Bean  objectgetbean (String name) managed in IOC container according to name  throws BeansException;   <t>t getbean (String name, class<t> requiredtype)  throws  Beansexception;  <t>t getbean (Class<t> requiredtype)  throws  Beansexception;  objectgetbean (String name, object... args)  throws  beansexception;  //determine if there is a Bean  booleancontainsbean (string name) with the specified name;   // Determine if the bean with the specified name is a singleton   booleanissingleton (string name)  throws  nosuchbeandefinitionexception;  //determines whether the bean of the specified name is a   booleanisprototype of type prototype (String  name)  throws nosuchbeandefinitionexception;  //determine if the bean with the specified name is a specific CLass type   booleanistypematch (string name, class<?> targettype)   throwsnosuchbeandefinitionexception;  //gets the Class type of the specified name Bean   class<?>gettype (String  name)  throws nosuchbeandefinitionexception;  //get all aliases for the specified name Bean   string[] Getaliases (string name);}

From the definition of beanfactory, you can see what the basic management capabilities of the container are.

Use Xmlbeanfactory to further analyze how such containers are implemented, and first see how xmlbeanfactory is defined:

public class Xmlbeanfactory Extendsdefaultlistablebeanfactory {privatefinal Xmlbeandefinitionreader reader = new XmlBe  Andefinitionreader (this);  Publicxmlbeanfactory (Resource Resource) throws Beansexception {this (resource,null); } publicxmlbeanfactory (Resource Resource, beanfactory parentbeanfactory) throwsbeansexception {super (Parentbeanfacto    RY);  This.reader.loadBeanDefinitions (Resource); }}

You can see that xmlbeanfactory inherited the defaultlistablebeanfactory.

Defaultlistablebeanfactory is a subclass of Abstractautowirecapablebeanfactory, And Abstractautowirecapablebeanfactory implements the Autowirecapablebeanfactory interface, it is autowirecapablebeanfactory inherited beanfactory.

Defaultlistablebeanfactory contains the important functions of the basic IOC container, which is used in many places, like ApplicationContext, In spring, defaultlistablebeanfactory is actually used as a default full-featured IOC container .

Continue to say xmlbeanfactory, according to the name we can know, xmlbeanfactory in addition to the implementation of basic functions, but also increased the reading of XML files defined by the Beandefeinition function. However, the processing of the file information defined by the XML file is not done directly by Xmlbeanfactory, but by initializing a xmlbeandefinitionreader in the xmlbeanfactory, which is handled by the reader object. In addition, when constructing xmlbeanfactory, you need to specify the source of the beandefinition, which needs to be encapsulated into the resource class in spring, and resource is the class used in spring to encapsulate I/O operations. For example, if the beandefinition information is defined as XML, you can construct resource using a method like classpathresource res = new Classpathresource ("Beans.xml"); It is then passed to the Xmlbeanfactory constructor so that the IOC container can locate the required beandefinition information to complete the container initialization and dependency injection process.

Classpathresource res = Newclasspathresource ("Springbeans.xml"); Xmlbeanfactory factory = newxmlbeanfactory (res); User user = (user) Factory.getbean ("UserBean");

This is the design and implementation of such containers, but in practical applications we usually do not use such containers (xmlbeanfactory even already deprecated), generally use a higher level of applicationcontext container.

In the design of ApplicationContext, on the one hand it inherits the Listablebeanfactory,autowriecapablebeanfactory in the beanfactory system, Hirearchicablebeanfactory and other interfaces, with the basic functions of beanfactory, on the other hand it by inheriting Messagesource,resourceloader, The Applicationeventpublisher interface allows it to have more advanced IOC container features.

Use this common class of filesystemxmlapplicationcontext to analyze such containers.

First look at the definition of Filesystemxmlapplicationcontext:

public classfilesystemxmlapplicationcontext extends abstractxmlapplicationcontext {     publicfilesystemxmlapplicationcontext ()  {  }  ...   Publicfilesystemxmlapplicationcontext (String[] configlocations, boolean refresh, Applicationcontext parent) Throws beansexception {      super ( parent);     setconfiglocations (configlocations);     if (refresh)  {         refresh ();       }  }    @Override   protectedresource getresourcebypath (string path)  {       if (Path != null && path.startswith ("/"))  {         path= path.substring (1);       }     returnnew filesyStemresource (path);   }} 

Some constructors are omitted from the code.

The main content of the ApplicationContext application context is already implemented in the base class Abstractxmlapplicationcontext, in Filesystemxmlapplicationcontext, As a specific application context, you need to implement the two functions associated with it:

One feature is that if the app uses Filesystemxmlapplicationcontext directly, to instantiate the support for this application context, and to start the refresh () process of the IOC container, this refresh will involve some column complex operations, and different containers implement these operations similar, so encapsulated in the base class, which is called directly here. It is also the initialization of the IOC container initiated by this method.

Another feature is the filesystemxmlapplicationcontext of how to load the XML's bean definition resources from the system files. Different application context implementations correspond to different ways of putting in read beandefinition. The rewritten Getresourcebypath can illustrate this point.

The details of how the refresh and Getresourcebypath methods are invoked, as well as how the XML file is handled in the example above, will be explained in detail in the next section of the IOC container initialization.

Then such containers are easy to use:

ApplicationContext context = new Filesystemxmlapplicationcontext ("Springbeans.xml"); User user = (user) Context.getbean ("UserBean");

Chapter II: Initialization of IOC containers >>


The study of the IOC container of Spring Technology Insider reading notes

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.