Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of IOC Control inversion in Spring

2025-04-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article shares with you the content of a sample analysis of IOC control reversal in Spring. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

1. What is IOC?

IOC-Inversion of Control, that is, inversion of control. It is not a technology, but a design idea.

The traditional way to create an object is directly through the new keyword, while spring creates the object through the IOC container, which means we give control of the creation to the IOC container. We can summarize IOC in one sentence:

IOC allows programmers to focus not on how to create objects, but on the operations after object creation, leaving object creation, initialization, destruction and other work to the spring container.

2. Share the easy-to-understand explanations of IoC and DI on Bromon's blog

IoC (Inversion of Control, inversion of control). This is the core of spring, throughout. The so-called IoC, for the spring framework, is that spring is responsible for controlling the life cycle of objects and the relationship between objects. What does this mean? to give a simple example, how do we find a girlfriend? The common situation is that we go around to see where there is a beautiful mm with a good figure, and then ask about their hobbies, qq number, phone number, ip number, iq number. Find a way to get to know them, give them what they want, and then hey. This process is complex and esoteric, and we must design and face each link by ourselves. The same is true of traditional program development. In an object, if you want to use another object, you must get it (new yourself, or query one from JNDI), and destroy the object (such as Connection, etc.) after using it. The object will always be coupled with other interfaces or classes.

So how does IoC do it? It's a bit like finding a girlfriend through matchmaking, introducing a third party between me and my girlfriend: a matchmaking agency. The matchmaking agency manages a lot of information about men and women. I can put forward a list to the matchmaker and tell it what kind of girlfriend I want to find, such as looking like Michelle Reis, having a figure like Lin Xilai, singing like Jay Chou, speed like Carlos, technical like Zidane, and so on. Then the matchmaker will provide a mm according to our request, and we just need to fall in love with her and marry her. To be simple and clear, if the candidate given to us does not meet the requirements, we will throw an exception. The whole process is no longer under my own control, but is controlled by a container-like institution such as matchmaking. This is the way Spring advocates development. All classes will be registered in the spring container, telling spring what you are and what you need, and then spring will take the initiative to give you what you want when the system is running properly, and give you what you need at the same time. The creation and destruction of all classes are controlled by spring, that is, the life cycle of an object is no longer controlled by the object that references it, but by spring. For a specific object, it used to control other objects, but now all objects are controlled by spring, so this is called control inversion.

3. Three ways for Spring container to create objects

Step 1: create the project, and then import the corresponding jar package, as shown below: (see the source download above for details)

Step 2: create the test object HelloIoc

Package com.ys.ioc;// this is the test object. We use IOC to create the object public class HelloIoc {public void sayHello () {System.out.println ("Hello IOC");}}

The traditional method of creating objects: the new keyword

/ / traditional object creation method-new @ Test public void testTradition () {HelloIoc hello = new HelloIoc (); hello.sayHello ();}

How do you create it here through a Spring container?

The first method: use 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:

Test the code:

/ * Spring container uses constructor to create object * / @ Test public void testCreateObjectByConstrutor () {/ / 1, launch spring container ApplicationContext context = new ClassPathXmlApplicationContext ("applicationContext.xml"); / / 2, extract data from spring container HelloIoc IOC = (HelloIoc) context.getBean ("helloIoc") / / 3. Call the method IOC.sayHello () through the object; / / create the object HelloIoc IOC2 = (HelloIoc) context.getBean ("helloIoc2") using the alias alias attribute of the configuration file; IOC2.sayHello ();}

We can manually add a no-argument constructor to the test class HelloIoc.java, and then execute the above test code, and we'll find that the constructor is called before the sayHello () method executes.

The second method: using the static factory method

First create the 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 ();}}

Then make the following configuration in applicationContext.xml:

Write test classes:

/ * * Spring container uses static factory method to create objects * / @ Test public void createObjectStaticFactory () {ApplicationContext context = new ClassPathXmlApplicationContext ("applicationContext.xml"); HelloIoc staticFactory = (HelloIoc) context.getBean ("helloStaticFactory"); staticFactory.sayHello ();}

Note: the spring container is only responsible for calling static factory methods, and the internal implementation of this static factory method is done by programmers.

The third method: using the example factory method

First create the instance factory class HelloInstanceFactory .java

Package com.ys.ioc;public class HelloInstanceFactory {public HelloInstanceFactory () {System.out.println ("instance factory method constructor");} / / use the instance factory method to create an object public HelloIoc getInstance () {HelloIoc instanceIoc = new HelloIoc (); return instanceIoc;}}

Then make the following configuration in applicationContext.xml:

Finally, write the test class:

/ * Spring container uses instance factory method to create objects * / @ Test public void createObjectInstanceFactory () {ApplicationContext context = new ClassPathXmlApplicationContext ("applicationContext.xml"); HelloIoc staticFactory = (HelloIoc) context.getBean ("instance"); staticFactory.sayHello () } 4. The first time for Spring containers to create objects: by default, objects are created when you start the spring container (objects are created when you encounter bean)

Test:

Step 1: let's add the default constructor to HelloIoc.java:

Step 2: add bean to the applicationContext.xml file (since we created the object in three ways above, there are already three bean in it)

Step 3: start the Spring container and check the number of times the no-parameter constructor is printed

The console print results are as follows:

Second: there is an attribute lazy-init= "default/true/false" in the configuration file bean of spring

①, if lazy-init is "default/false" create an object when you start the spring container (default)

②. If lazy-init is "true", the object is created only when context.getBean.

We tested the lazy-init= "true".

We tested through breakpoint debugging:

Then proceed to the following:

In the first case, when you start the spring container, check the correctness of the spring container configuration file. If combined with tomcat, if the spring container does not start normally, the whole tomcat cannot start normally. But this disadvantage is that some bean is put in memory too early, if there is data, it is a consumption of memory.

Conversely, in the second case, memory consumption can be reduced, but errors are not easy to find.

5. Scope in spring's bean: "singleton/prototype/request/session/globalsession" 1. The default value of 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" >

Verify:

/ / the default generated object of spring container is singleton scope= "singleton" @ Test public 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} II, scope= "prototype"

Multiple patterns, and the object is not created when the spring container is started, but when the bean is obtained

Configuration in the applicationContext.xml file:

Verify:

/ / the default generated object of the spring container is scope= "prototype" @ Test public 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: in singleton mode, objects are created when you start the spring container; in multiple cases, objects are not created when you start the container, but only when you get the bean

6. Spring container life cycle

Create SpringLifeCycle.java

Life cycle of package com.ys.ioc;/** * Spring container * @ author hadoop * * / public class SpringLifeCycle {public SpringLifeCycle () {System.out.println ("SpringLifeCycle");} / / define initialization method public void init () {System.out.println ("init...") } / / define the destruction method public void destroy () {System.out.println ("destroy...");} public void sayHello () {System.out.println ("say Hello...");}}

ApplicationContext.xml

Test:

/ / initialization and destruction of spring container @ Test public 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: declaration cycle of the spring container

1. Spring container creates objects

2. Execute the init method

3. Call your own method

4. Execute the destroy method when the spring container is closed

Note: when scope is "prototype", the destroy method is not called when the close () method is called

Thank you for reading! This is the end of the article on "sample Analysis of IOC Control inversion in Spring". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report