Home Java javaTutorial Concept and analysis of IOC

Concept and analysis of IOC

Jul 17, 2017 pm 01:36 PM

Inversion of Control (Inversion of Control, English abbreviation IoC) is an important feature of the framework and is not a special term for object-oriented programming. It has nothing to do with Dependency Injection (DI) and Dependency Lookup.

1. The concept of IOC: IOC (Inversion of Control) means inversion of control. First, we have to figure out what is being inverted. Most of the business logic in Java programs requires multiple objects to be completed collaboratively. Usually, when each object uses its cooperative object, it must use syntax like new object() to complete the application for the cooperative object. In this way, the degree of coupling between objects is high. The idea of ​​IOC is that the Spring container implements the creation and coordination of these interdependent objects. The object only needs to care about the business logic itself. In this respect, the responsibility of how an object obtains its collaborating objects is reversed . In fact, IOC has a more appropriate name called DI (Dependency Injection), which is dependency injection.

To give a popular example: Suppose there is a company now. The company needs employees to complete corresponding work. Then the company needs to find ways to find talents in this field to work for the company based on its needs. . This is a traditional way. Suppose we now have a recruitment website. All talents register their information on the website and write down their skills and areas of expertise. When a company needs talents, recruitment The website provides specific talents to the company, so the company only needs to publish employment requirements. The enterprise in this example can be considered as the business class EnterpriseService, and the talent is the assistance class Employee that the business class needs to complete its work. Then the recruitment website is equivalent to the IOC container

<code class="java"><span class="hljs-number"><span style="color: #000000"><br/>1 . 传统获取对象的方式<br/></span></span></code>
Copy after login
public class EnterpriseService {

    Employee employee = new Employee();//自己通过new Object()方式获取对象public void service() {
        employee.doSomething();
    }
}
Copy after login
<code class="java"><span class="hljs-number"><span class="hljs-keyword"><span class="hljs-class"><span class="hljs-keyword"><span class="hljs-title"><span class="hljs-keyword"><span class="hljs-comment"><span class="hljs-function"><span class="hljs-keyword"><span class="hljs-keyword"><span class="hljs-title"><span class="hljs-params"><span class="hljs-number">2 . 使用IOC容器方式<br/></span></span></span></span></span></span></span></span></span></span></span></span></span></code>
Copy after login
public class EnterpriseService {

    @Autowired
    Employee employee;//由容器完成对象的获取以及后续生命周期的管理public void service() {
        employee.doSomething();
    }
}
Copy after login

2. Analysis of the principle of DI
The principle of DI is very simple and is implemented based on the reflection mechanism of java. When we use spring, we will have an xml configuration file. This file is used to describe the dependencies between beans. The IOC container maintains and manages all beans based on this file, and provides advanced tasks such as bean instance caching, life cycle management, bean instance proxy, event publishing, and resource loading.
When IOC is started, it will assist in reading and parsing resource files through Resource and ResourceLoader, and store the configuration information of the Bean in the file. Then when instantiating the Bean, it will use the corresponding class loader through Reflection calls the setter method of the Bean and injects the properties configured in the configuration file into the instance to complete the creation of the object.

3. Related content
1. From the injection method point of view, there are three injection methods: Constructor injection, attribute injection, interface injection . Spring supports constructor injection and property injection.
2. BeanFactory is a class factory, which is the core interface of the spring framework. It provides an advanced IOC configuration mechanism. BeanFactory makes it possible to manage different types of java objects. Perhaps, ApplicationContext is based on BeanFactory and provides more application-oriented features, such as internationalization support and framework event system.
3. When starting the IOC container through BeanFactory, the beans defined in the configuration file will not be initialized immediately. The initialization action occurs when the first call is made. For singleton Beans, the BeanFactory will cache the Bean instance (implemented based on HashMap), so when the getBeans method is called again, the Bean instance will be obtained directly from the cache of the IOC container.
4. The main implementation classes of ApplicationContext are ClassPathXmlApplication and FileSystemXmlApplicationContext. WebApplicationContext inherits ApplicationContext and is specially prepared for web applications. It allows searching and loading from paths relative to the root directory of web applications. Configuration file (implemented using the Resource interface and ResourceLoader interface). A ServletContext reference can be obtained from the WebApplicationContext, and the entire WebApplicationContext will be placed in the ServletContext as a property so that the web application environment can access the spring application context. Three bean scopes have been added to the web application: request, session, and global session. The initialization method of WebApplicationContext is different from BeanFactory and ApplicationContext, because it requires a ServletContext instance, that is, it must have a web container to complete the startup work.
5 .A major difference between the initialization of ApplicationContext and the initialization of BeanFactory is: ApplicationContext instantiates all beans when initializing the application context. Another major difference is: ApplicationContext will use the java reflection mechanism to automatically identify the BeanPostProcessor, InstantiationAwareBeanPostProcessor and BeanFactoryPostProcessor defined in the configuration file, and automatically register them into the application context, while BeanFactory needs to be passed manually in the code addBeanPostProcessor() method to register.
6. For beans with scope="singleton", spring will cache the beans in the IOC container, return the bean reference to the caller, and continue to perform subsequent life management of these beans. The same bean is returned every time the getBeans method is called. For beans with scope="prototype", spring is no longer responsible for the life management of the bean after returning the bean to the caller. Each time the getBeans method is called, a new bean will be returned.

The above is the detailed content of Concept and analysis of IOC. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How does Java's classloading mechanism work, including different classloaders and their delegation models? How does Java's classloading mechanism work, including different classloaders and their delegation models? Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache? How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache? Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading? How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading? Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution? How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution? Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management? How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management? Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

See all articles