Spring Details (ii)------IOC control reversal

Source: Internet
Author: User
Tags ip number

I believe that when it comes to Spring, many people will blurt out the concepts of IOC (inversion of Control), DI (Dependency injection), AOP, and so on, which are often asked by interviewers. So this blog we will explain in detail the IOC control inversion.

PS: this blog source download link: http://pan.baidu.com/s/1miwZIf2 Password: OQUC

1. What is the IOC?

Ioc-inversion of control, which controls inversion. It is not a technology, but a design idea.

Traditional methods of creating objects are directly through the new keyword , while spring creates objects through the IOC container, which means we give control of the creation of the object to the IOC container. We can summarize the IOC in a word:

  IOC lets programmers not focus on how to create objects, but focus on the operation after the creation of objects, the creation of objects, initialization, destruction and other work to the spring container to do.

2. ShareBromon's blog on the IOC and Di Easy-to-understand explanation

IoC (inversion of control, inversion of controls). This is the core of spring, throughout. The so-called IOC, for the spring framework, is the responsibility of spring to control the object's life cycle and the relationship between objects. What does that mean, for example, how do we find a girlfriend? The common situation is that we go everywhere to see where there is a beautiful body and good mm, and then inquire about their interests, QQ number, telephone number, IP number, IQ number ..., find ways to know them, give them what they want, then hey ... The process is complex and profound, and we have to design and face each link ourselves. The same is true of traditional program development, in an object, if you want to use another object, you have to get it (your own new one, or a query from Jndi), after the use of the object will be destroyed (such as connection, etc.), the object will always and other interfaces or classes together.

So how does the IOC do it? It's kind of like finding a girlfriend through a dating agency, introducing a third party between me and my girlfriend: the Marriage Institute. Matchmaking management of a lot of men and women's information, I can give a list of matchmaking, tell it I want to find a girlfriend, such as like Michelle Reis, figure like Lin Xire, singing like Jay Chou, speed like Carlos, technology like Zidane, and then the matchmaking will be according to our requirements, provide a mm, We just have to go to love her and get married. As simple as it is, if a matchmaking person doesn't meet our requirements, we'll throw an exception. The whole process is no longer controlled by myself, but by a similar container-like institution that has a matchmaking system. This is how spring advocates for development, and all classes are registered in the spring container, telling spring what you are, what you need, and then spring will give you what you want when the system runs to the right time, as well as handing you over to other things that need you. All classes are created and destroyed by spring, which means that the object that controls the lifetime of the object is no longer a reference to it, but spring. For a specific object, it was previously controlled by other objects, and now all objects are controlled by spring, so this is called control inversion.

3. Spring container Three ways to create objects

  The first step: Create the project, and then import the appropriate jar package, such as: (see the source download above for details)

Step Two: Create a Test object Helloioc

Package com.ys.ioc;//This is a test object, we create object public class Helloioc {public void SayHello () {System.out.println ("Hello IOC") via IOC ;}}

Traditional methods for creating objects: the New keyword

The traditional method of creating objects----New@testpublic void Testtradition () {Helloioc Hello = new Helloioc (); Hello.sayhello ();}

  

How do we create this through the Spring container?

  The first method: Using the default construction method

Create a new Applicationcontext.xml file in the SRC directory, which is the spring configuration file and add the following code:

<?xml version= "1.0" encoding= "UTF-8"? ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation= "Http://www.springframework.org/schema/beans           http://www.springframework.org/schema/beans/spring-beans.xsd ">    <!--the first way to create an object: Take advantage of the parameterless constructor ID: Unique Identifier class: Class-Full-class name--    <bean id= "Helloioc" class= "Com.ys.ioc.HelloIoc" ></bean>       <!-- Alias attribute  name: And Bean's id attribute corresponds to--><alias name= "HELLOIOC" alias= "HELLOIOC2"/></beans>

Test code:

/** *  Spring container uses constructors to create objects */@Testpublic void Testcreateobjectbyconstrutor () {//1, Start Spring container ApplicationContext context = new Classpathxmlapplicationcontext ("Applicationcontext.xml");//2, extracting data from the Spring container helloioc IOC = (HELLOIOC) Context.getbean ("Helloioc");//3, call method by Object Ioc.sayhello ();//Use Profile alias Alias property to create object Helloioc IOC2 = (HELLOIOC) Context.getbean ("HelloIoc2"); Ioc2.sayhello ();}

We can manually add the parameterless construction method in the test class Helloioc.java, and then execute the above test code, and find that the construction method is called before the SayHello () method executes.

  Second approach: using Static factory methods

  First create a static factory class Hellostaticfactory.java

Package Com.ys.ioc;public class Hellostaticfactory {public hellostaticfactory () {System.out.println (" Hellostaticfactory constructor ");} Static Factory method public static Helloioc GetInstances () {return new HELLOIOC ();}}

The following configuration is then performed in Applicationcontext.xml:

<!--    The second way to create objects: Using the static Factory method    Factory-method: Static method of acquiring objects for static factory classes class    : Full class name of static factory class---        <bean Id= "Hellostaticfactory" factory-method= "getinstances" class= "Com.ys.ioc.HelloStaticFactory" ></bean>

To write a test class:

/** * Spring containers Create objects using static factory methods */@Testpublic void Createobjectstaticfactory () {ApplicationContext context = new Classpathxmlapplicationcontext ("Applicationcontext.xml"); HELLOIOC staticfactory = (HELLOIOC) context.getbean ("Hellostaticfactory"); Staticfactory.sayhello ();}

  Note: The spring container is only responsible for invoking the static factory method, and the internal implementation of this static factory method is done by the programmer

  Third approach: using instance factory methods

  First create the Instance factory class Helloinstancefactory. java

Package Com.ys.ioc;public class Helloinstancefactory {public helloinstancefactory () {System.out.println ("instance factory method constructors" );} Use instance factory method to create object public HELLOIOC getinstance () {HELLOIOC instanceioc = new Helloioc (); return INSTANCEIOC;}}

The following configuration is then performed in Applicationcontext.xml:

<!--    The third Way to create objects: Using the instance factory method    Factory-bean: Specifies the Beanid Factory-method with the factory method in the current spring    : Factory method Name--      <bean id= "instancefactory" class= "com.ys.ioc.HelloInstanceFactory" ></bean>      <bean id= " Instance "factory-bean=" Instancefactory "factory-method=" getinstance "></bean>    

Finally write the test class:

/** * Spring Container uses instance factory method to create object */@Testpublic void Createobjectinstancefactory () {ApplicationContext context = new Classpathxmlapplicationcontext ("Applicationcontext.xml"); HELLOIOC staticfactory = (HELLOIOC) Context.getbean ("instance"); Staticfactory.sayhello ();}

  

4. Time when the Spring container creates objects

  First: By default, the spring container is started to create the object (the object is created when the bean is encountered)

Test:

The first step: we add the default constructor method in Helloioc.java:

  

Step Two: Add the bean in the Applicationcontext.xml file (since we created the object in three ways, there are already three beans in it)

Step three: Start the Spring container to see how many times the parameterless constructor is printed

  

The console prints the following results:

  

The second: there is an attribute lazy-init= "Default/true/false" in spring's configuration file Bean

①, if Lazy-init is "Default/false" when you start the Spring container (by default)

②, if Lazy-init is "true", the object is created at Context.getbean

We tested the lazy-init= "true" condition

  

We test the debug via breakpoints:

  

Then proceed to the following side:

  

In the first case, when you start the spring container, check the correctness of the spring container configuration file, and if you combine Tomcat, the entire Tomcat will not start properly if the spring container does not start properly. But the disadvantage is to put some beans prematurely in memory, if there is data, it is a consumption of memory.

Conversely, in the second case, you can reduce the consumption of memory, but it is not easy to find errors

5. Scope in Spring Bean: "Singleton/prototype/request/session/global session"

the value of the default scope is singleton, that is, the resulting object is a singleton

Configuration in the Applicationcontext.xml file:

<bean id= "Helloioc" scope= "singleton" class= "Com.ys.ioc.HelloIoc" ></bean>

Verify:

The spring container default produces an object that is a singleton scope= "singleton" @Testpublic Void Test_scope_single_createobject () {ApplicationContext context = new Classpathxmlapplicationcontext ("Applicationcontext.xml"); HELLOIOC hello1 = (HELLOIOC) context.getbean ("Helloioc"); HELLOIOC Hello2 = (HELLOIOC) context.getbean ("Helloioc"); System.out.println (Hello1.equals (Hello2)); True

  Second, scope= "prototype"

Multi-instance mode, and the spring container does not create objects when it is started, but only when the bean is obtained

Configuration in the Applicationcontext.xml file:

<bean id= "HELLOIOC" scope= "prototype" class= "Com.ys.ioc.HelloIoc" ></bean>

Verify:

The spring container default produces an object that is a singleton scope= "prototype" @Testpublic void Test_scope_prototype_createobject () {ApplicationContext context = new Classpathxmlapplicationcontext ("Applicationcontext.xml"); HELLOIOC hello1 = (HELLOIOC) context.getbean ("Helloioc"); HELLOIOC Hello2 = (HELLOIOC) context.getbean ("Helloioc"); System.out.println (Hello1.equals (Hello2)); False

  

  Summary: When you start the Spring container in singleton mode, the object is created; in multiple cases, launching the container does not create the object, and the object is created when the bean is obtained.

5. Spring Container life cycle

Create Springlifecycle.java

Package com.ys.ioc;/** * Spring container life cycle * @author Hadoop * */public class Springlifecycle {public springlifecycle () {System . OUT.PRINTLN ("Springlifecycle");} Define initialization method public void init () {System.out.println ("init ...");} Define the Destroy method public void Destroy () {System.out.println ("destroy ..."); public void SayHello () {System.out.println ("Say Hello ...");}}

Applicationcontext.xml

<!--life cycle--  

Test:

Spring container initialization and destruction @testpublic void Testspringlifecycle () {ApplicationContext context = new Classpathxmlapplicationcontext ("Applicationcontext.xml"); springlifecycle Hello = (springlifecycle) context.getbean ("springlifecycle"); Hello.sayhello ();// Destroy Spring container Classpathxmlapplicationcontext ClassContext = (classpathxmlapplicationcontext) context; Classcontext.close ();}

  

The console prints as follows:

  

Analysis: The declaration period of a spring container

1. Spring Container Creation Object
2. Execute the Init method
3. Call your Own method
4. Execute the Destroy method when the spring container is closed

Note: When the scope is "prototype", the Destroy method is not called when the Close () method is called

Spring Details (ii)------IOC control reversal

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.