The three blog posts in front of us briefly explain why we use ioc[examples to explain the IOC principles of (ii), and spring [popular explanation] (iii) and two common implementations of dependency injection (iv), these are the basics of learning the spring IOC container at first. Of course, only with these foundations, we can go to today more detailed analysis of spring source, in-depth understanding of the IOC.
I'll review the IOC briefly, and then introduce the basic principles of the IOC based on an example. Less nonsense, let's start with the topic of this blog post:
What is IOC
IOC container, the most important thing is to complete the creation of objects and maintain the dependencies of objects and so on.
The so-called inversion of control, including two parts: one is control, the other is inversion, is the traditional way to implement the object by code to create, maintain the dependency of the object, back to the container to help management and implementation. So we have to create a container, and we need a description to let the container create the relationship between the object and the object.
How the IOC container is initialized and created by the object. Spring requires only four steps:
1. Positioning
We know that object and object relationships can be represented by semantic configuration files such as xml,properties files, how do we locate these files? Spring sets the resource loader and resource positioning methods for us, possibly Classpath (classpath), filesystem (file system), or URL network resources, or Web containers (ServletContext).
2. Load in
After we locate the resource file, we need to load the resource files and, before creating the IOC container, if there are already containers, we need to destroy and close the existing containers to ensure that the newly established IOC container is used.
3. Analysis
With the configuration file, the configuration file also needs to be parsed. Different profiles do not have the same description of objects, and custom declarations must be translated into a unified description definition.
4. Registration
Registers the parsed beandefinition with the IOC container, at which point the IOC container initialization is complete.
Here, I believe you must have a further understanding of the IOC container. Let's take a look at the core of the IOC in the original example.
The core-beanfactory of the IOC
Package diagram for the project:
Spring's configuration file:
<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:tx= " Http://www.springframework.org/schema/tx "xsi:schemalocation=" Http://www.springframework.org/schema/beans http:/ /www.springframework.org/schema/beans/spring-beans-4.1.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www. Springframework.org/schema/aop/spring-aop-4.1.xsd Http://www.springframework.org/schema/tx Http://www.springfram Ework.org/schema/tx/spring-tx-4.1.xsd "><!--using Spring to manage object creation, as well as object dependencies--><bean id=" Userdao4mysql " class= "Com.tgb.spring.dao.UserDao4MysqlImpl"/><bean id= "userdao4oracle" class= " Com.tgb.spring.dao.UserDao4OracleImpl "/><bean id=" Usermanager "class=" Com.tgb.spring.manager.UserManagerImpl "><!--(1) Usermanager uses USERDAO,IOC to automatically create the corresponding Userdao implementation, which is managed by the container-- <!--(2) in UsermanagerProvides a constructor in which spring will inject the Userdao implementation (DI)--><!--(3) to let spring manage the creation and dependency of our objects, the dependencies must be configured in spring's core configuration file-->< Property Name= "Userdao" ref= "Userdao4oracle" ></property></bean></beans>
Business Logic Layer:
Usermanager interface: How to add a user
Public interface Usermanager {public void AddUser (String username,string password);}
Usermanager Implementation
Import Com.tgb.spring.dao.userdao;public class Usermanagerimpl implements Usermanager{private Userdao userdao;// Use the Set value method to assign the public void Setuserdao (Userdao userdao) {This.userdao = Userdao;} @Overridepublic void AddUser (string userName, string password) {userdao.adduser (userName, password);}}
data Access layer:
Userdao interface: How to add Users
Public interface Userdao {public void AddUser (String username,string password);}
two implementations of Userdao (MySQL and Oracle)
public class Userdao4mysqlimpl implements userdao{@Overridepublic void AddUser (string userName, string password) {// Print access to MySQL information about System.out.println ("Userdao4mysqlimpl.adduser");}}
public class Userdao4oracleimpl implements userdao{@Overridepublic void AddUser (string userName, string password) {// Print information about access to Oracle System.out.println ("Userdao4oracleimpl.adduser");}}
Client:
Import Org.springframework.beans.factory.beanfactory;import Org.springframework.context.support.classpathxmlapplicationcontext;import Com.tgb.spring.manager.UserManager; public class Client {public static void main (string[] args) {Beanfactory factory = new Classpathxmlapplicationcontext ("app Licationcontext.xml ");//Get Usermanagerusermanager Usermanager = (usermanager) factory.getbean (" UserManager ") in the IOC container //usermanager using Userdao, there is already a dependency usermanager.adduser ("Jiuqiyuliang", "123456") in the config file;}}
Run:
In our client code, when we initialize the IOC container, we are using spring's most central interface,--beanfactory, which can be said to be the heart of spring. Spring's IOC revolves around the beanfactory. Let's take a look at some of the most basic services that spring provides to us through the class diagram:
From here we can see that beanfactory is the topmost interface that defines the basic functions of the IOC container. Where Beanfactory is the topmost interface class, it defines the basic functional specification of the IOC container, Beanfactory has three subclasses: Listablebeanfactory, Hierarchicalbeanfactory and Autowirecapablebeanfactory. But from this we can find that the final default implementation class is Defaultlistablebeanfactory, and he implements all the interfaces. so why define so many levels of interfaces? Refer to the source code and description of these interfaces found that each interface has his use of the occasion, it is mainly to distinguish between Spring in the process of the object during the transfer and conversion process, the object of the data access restrictions. For example, the Listablebeanfactory interface indicates that these beans are a list, and hierarchicalbeanfactory indicates that the beans are inherited, that is, each bean may have a parent bean. The Autowirecapablebeanfactory interface defines the automatic assembly rules for the Bean. These four interfaces collectively define the Bean's collection, the relationship between the beans, and the most basic IOC container interface for the bean row beanfactory
We look through the source of Beanfactory to provide us with the most basic services:
Public interface Beanfactory {/** * used to dereference a {@link Factorybean} instance and distinguish it from * beans < ;i>created</i> by the Factorybean. * Escape definition for Factorybean, because if the object retrieved using the BEAN's name is a factory-generated object, * if you need to get the factory itself, you need to escape */string Factory_bean_prefix = "&" ;/** * Return An instance, which could be shared or independent, of the specified bean. * Based on the Bean's name, gets the bean instance */object getbean (String name) throws beansexception;/** * Return An instance in the IOC container, which May is s Hared or independent, of the specified bean. * The Bean instance is obtained according to the Bean's name and class type, and the type security authentication mechanism is added. */<t> T Getbean (String name, Class<t> requiredtype) throws beansexception;/** * Return The Bean instance that Uniquely matches the given object type, if any. * The Bean instance is obtained according to class type, and the type security authentication mechanism is added. */<t> T Getbean (class<t> requiredtype) throws beansexception;/** * Return An instance, which could be shared or Independent, the specified bean. * */object Getbean (String name, Object ... args) throwsbeansexception;/** * Return An instance, which could be shared or independent, of the specified bean. */<t> T Getbean (class<t> requiredtype, Object ... args) throws beansexception;/** * Does this bean factory cont Ain a bean definition or externally registered Singleton * Instance with the given name? * Provide a search for the bean to see if the IOC container has the name of the Bean */boolean Containsbean (String name);/** * Is this bean a shared singleton? That is, would {@link #getBean} always * Return the same instance? * Get the Bean instance based on the bean name, and also determine if the bean is a singleton */boolean Issingleton (String name) throws nosuchbeandefinitionexception;/** * is This bean a prototype? That is, would {@link #getBean} always return * Independent instances? */boolean Isprototype (String name) throws nosuchbeandefinitionexception;/** * Check whether the bean with the given name M Atches the specified type. * More specifically, check whether a {@link #getBean}-the given name * would return an object-is assignable To the specified target type.* */boolean Istypematch (String name, class<?> targetType) throws nosuchbeandefinitionexception;/** * Determine the Type of the bean with the given name. More specifically, * Determine the type of object that {@link #getBean} would return for the given name. * Get the Class type of the bean instance */class<?> getType (String name) throws nosuchbeandefinitionexception;/** * Return the aliases fo R the given bean name, if any. * All of those aliases point to the same beans when used in a {@link #getBean} call. * Get the Bean alias, if retrieved according to the alias, then its original name will also be retrieved */string[] getaliases (String name);
Summarize
Beanfactory only defines or regulates the basic behavior of the IOC container, and there is no concrete implementation at all.
In the next blog post I will give you a detailed introduction of "Dick Silk version" beanfactory and high-handsome rich version of Beanfactory. Please pay attention.
"The Way to SSH" Spring's IOC-level depth--the fundamental beanfactory of the IOC of Source parsing (v)