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

IOC, which explains the core idea of Spring framework in detail

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

WeChat account: GitShare

Official account of Wechat: a straw that loves to toss.

If you have any questions or suggestions, please leave a message on the official account [1]

Previous continuation

In order to help the majority of SpringBoot users to "know what it is, but also need to know why", the author will deeply analyze the SpringBoot2.0.0.RELEASE version through a series of SpringBoot articles, so that you can have a deep understanding of its internal working principle.

What is No.1 Spring?

In order to let more friends know about Spring, first of all, popular science about Spring! Interested friends can visit the official website of Spring at https://spring.io/

The Spring Framework provides a comprehensive programming and configuration model for modern Java-based enterprise applications-on any kind of deployment platform.

Spring Framework provides a comprehensive programming and configuration model for modern Java-based enterprise applications-on any type of deployment platform.

Overall: Spring is an one-stop lightweight open source framework for hierarchical Java SE/EE applications.

Advantages of No.2 Spring

A key element of Spring is application-level infrastructure support: Spring focuses on the "pipeline" of enterprise applications so that teams can focus on application-level business logic without making unnecessary connections to specific deployment environments.

It is convenient to decouple and simplify development. Through the IoC container provided by Spring, we can hand over the dependency relationship between objects to Spring to avoid the high degree of program coupling caused by hard coding.

AOP programming support, through the AOP function provided by Spring, it is convenient to carry out aspect-oriented programming.

With the support of declarative transactions, in Spring, we can extricate ourselves from the tedious transaction management code, manage transactions flexibly in a declarative way, and improve the efficiency and quality of development.

To facilitate program testing, you can do almost all the testing work in a non-container-dependent programming way.

It is easy to integrate all kinds of excellent frameworks, and Spring provides direct support for all kinds of excellent frameworks.

Architecture of No.3 Sprnig

The whole Spring framework can be divided into five main modules according to its functions. These five modules provide almost everything needed for enterprise applications, including persistence layer, business layer and presentation layer. This is why Spring is an one-stop framework. IoC and AOP are the core of Spring.

1. Core module (Core Container)

The core module of Spring implements the function of IoC, which separates the dependency between classes from the code and describes the dependency relationship in the way of configuration. The IoC container is responsible for class creation, management, acquisition, and so on. BeanFactory interface is the core interface of Spring framework, which implements many core functions of container.

The Context module is built on the core module and extends the functions of BeanFactory, including internationalization, resource loading, mail service, task scheduling and so on. ApplicationContext is the core interface of Context module.

Expression language (Expression Language) is an extension of Unified expression language (EL), which supports setting and getting object properties, calling object methods, manipulating arrays, collections, and so on. It makes it easy to interact with the Spring IoC container through expressions.

2. AOP module

The Spring AOP module provides an implementation that meets the AOP Alliance specification and integrates AspectJ, a framework at the AOP language level. The coupling can be reduced by AOP.

3. Data access Integration Module (Data Access/Integration)

The module includes JDBC, ORM, OXM, JMS and transaction management.

Transaction module: this module is used for Spring management transactions, as long as the Spring management objects can get the benefits of Spring management transactions, there is no need for transaction control in the code, and supports programming and declarative transaction management.

JDBC module: provides a sample template for JBDC, which eliminates the traditional lengthy JDBC coding and necessary transaction control, and enjoys the benefits of Spring managing transactions.

ORM module: provides seamless integration with popular object-relational mapping frameworks, including Hibernate, JPA, MyBatis, etc. And you can use Spring transaction management without additional control over the transaction.

OXM module: provides an implementation of mapping Object/XML, mapping java objects to XML data, or mapping XML data to java objects. The Object/XML mapping implementation includes JAXB, Castor, XMLBeans, and XStream.

JMS module: for JMS (Java Messaging Service), provides a set of "message producer, message consumer" templates for easier use of JMS,JMS for sending messages between two applications or in distributed systems for asynchronous communication.

4. Web module

This module is based on ApplicationContext module and provides the function of Web application. Such as file upload, FreeMarker and so on.

Spring can integrate MVC frameworks such as Struts2. Spring itself provides the MVC framework Spring MVC.

5. Test module

Spring can do almost all testing work in a non-container-dependent programming way, supporting testing frameworks such as JUnit and TestNG.

No.4, what is IOC?

IOC is an acronym for Inversion of Control, also known as "inversion of control". In 1996, Michael Mattson first proposed the concept of IOC in an article on object-oriented frameworks.

To put it simply, the complex system is decomposed into cooperative objects. After these object classes are encapsulated, the internal implementation is transparent to the outside, thus reducing the complexity of solving the problem, and can be flexibly reused and extended.

The view put forward by IOC theory is generally like this: decoupling between dependent objects is realized with the help of a "third party" (IOC container).

In 2004, Martin Fowler discussed the same question: since IOC is an inversion of control, then "which aspects of control have been reversed?" After detailed analysis and argumentation, he came to the answer: "the process of obtaining dependent objects has been reversed."

After the control is reversed, the process of obtaining dependent objects is changed from self-management to active injection by the IOC container. So he gave "inversion of control" a more appropriate name, "dependency injection (Dependency Injection)."

The so-called dependency injection is that the IOC container injects some dependency into the object dynamically during the run time.

Dependency injection (DI) and control inversion (IOC) describe the same thing from different angles, that is, through the introduction of IOC container, the use of dependency injection to achieve decoupling between objects.

Summary:

The so-called control inversion is to reverse the object creation and dependent code that we need to implement in our code to the container to help implement it.

Another term for IOC (Inversion of Control) is called DI (Dependency Injection), that is, dependency injection. It is not a kind of technical realization, but a kind of design idea.

From a technical point of view, IOC is actually reflection programming. The class object is generated dynamically through the class name (string).

IoC container: the most important thing is to complete the object creation and dependency management injection.

No.5 Spring IOC Container (BeanFaoctory system)

As a top-level interface class, BeanFactory defines the basic functional specifications of the IOC container. Its source code is as follows:

Public interface BeanFactory {

/ * *

* escape definition of FactoryBean, because if the object retrieved by FactoryBean using the name of bean is a factory-generated object, if you need to get the factory itself, you need to escape

, /

String FACTORY_BEAN_PREFIX = "&"

/ * *

* get the bean instance in the IOC container according to the name of bean.

, /

Object getBean (String name) throws BeansException

/ * *

* the bean instance is obtained according to the name and Class type of bean, and a type safety verification mechanism is added

, /

T getBean (String name, @ Nullable Class requiredType) throws BeansException

/ * *

* get the bean instance based on the name and Class type of bean, and the parameters when args instantiates bean

, /

Object getBean (String name, Object... Args) throws BeansException

/ * *

* obtain the bean instance according to the Class type class of bean

, /

T getBean (Class requiredType) throws BeansException

/ * *

* obtain the bean instance according to the Class type class of bean, and instantiate the parameters of bean by args

, /

T getBean (Class requiredType, Object...) Args) throws BeansException

/ * *

* provide a search for bean to see if there is a bean with that name in the IOC container

, /

Boolean containsBean (String name)

/ * *

* get the bean instance based on the bean name, and determine whether the bean is a singleton or not

, /

Boolean isSingleton (String name) throws NoSuchBeanDefinitionException

/ * *

* [2.0.3 add] get the bean instance based on the bean name, and determine whether the bean is a prototype or not

, /

Boolean isPrototype (String name) throws NoSuchBeanDefinitionException

/ * *

* check whether the getBean call with the given name will return an object that can be assigned to the specified target type.

, /

Boolean isTypeMatch (String name, ResolvableType typeToMatch) throws NoSuchBeanDefinitionException

/ * *

* [added in version 2.0.1] checks whether a getBean call with a given name will return an object that can be assigned to the specified target type.

, /

Boolean isTypeMatch (String name, @ Nullable Class typeToMatch) throws NoSuchBeanDefinitionException

/ * *

* get the Class type of bean instance

, /

@ Nullable

Class getType (String name) throws NoSuchBeanDefinitionException

/ * *

* get the alias of bean. If you retrieve it according to the alias, the original name will also be retrieved.

, /

String [] getAliases (String name)

}

The root interface used to access the Spring bean container.

The BeanFactory implementation should support the standard bean lifecycle interface as much as possible, and the complete initialization method and its standard order are:

-1. SetBeanName of BeanNameAware

-2. SetBeanClassLoader of BeanClassLoaderAware

-3. SetBeanFactory of BeanFactoryAware

-4. SetEnvironment of EnvironmentAware

-5. SetEmbeddedValueResolver of EmbeddedValueResolverAware

-6. SetResourceLoader of ResourceLoaderAware (only applicable to runtime application context)

-7. SetApplicationEventPublisher of ApplicationEventPublisherAware (only applicable to runtime application context)

-8. SetMessageSource of MessageSourceAware (applicable to runtime application context only)

-9. SetApplicationContext of ApplicationContextAware (applicable to runtime application context only)

-10. SetServletContext of ServletContextAware' (only applicable to runtime application context)

11. PostProcessBeforeInitialization method of BeanPostProcessors

-12. AfterPropertiesSet of InitializingBean

Customize an initialization method (init-method)

-14. PostProcessAfterInitialization method of BeanPostProcessors

When you close BeanFactory, the following lifecycle methods apply:

-1. PostProcessBeforeDestruction method of DestructionAwareBeanPostProcessors

-2. DisposableBean's destroy

-3. Customize a termination method (destroy-method)

1. Inheritance relationship of BeanFactory

ListableBeanFactory

The extension of the BeanFactory interface is implemented by the bean factory to provide enumeration of bean instances in the container.

HierarchicalBeanFactory

Can be implemented as a bean factory as part of a hierarchical structure. Provides access to the parent container.

Public interface HierarchicalBeanFactory extends BeanFactory {

/ * *

* return to its parent factory, if no Null is returned

, /

@ Nullable

BeanFactory getParentBeanFactory ()

/ * *

* returns whether the current bean factory context has a bean with a given bean name, ignores the factory context defined in its inheritance hierarchy, and only looks for it in the current hierarchy.

, /

Boolean containsLocalBean (String name)

}

AutowireCapableBeanFactory

Extensions to the BeanFactory interface will be implemented by BeanFactory that can be automatically assembled, provided they want to expose this functionality for existing bean instances.

Add and integrate other framework functions. If you integrate WebWork, you can use Spring to manage Actions and so on.

SimpleJndiBeanFactory

Simple implementation of Spring's BeanFactory interface based on JNDI, which does not support enumerating bean definitions.

ConfigurableBeanFactory

Is a subclass of HierarchicalBeanFactory and provides the ability to configure BeanFactory.

ConfigurableListableBeanFactory

Is a subclass of ListableBeanFactory, ConfigurableBeanFactory, and AutowireCapableBeanFactory, and provides the ability to analyze and modify bean definitions and pre-instantiate singletons.

ApplicationContext

The application context interface, which has been analyzed in Spring's Context article.

2. Initialization of IOC container in Spring

In Spring, the initialization of the IOC container is started by the refresh () method, and there are three basic processes:

Resource location of 1.BeanDifinition

Loading and parsing of 2.BeanDifinition

Registration of 3.BeanDifinition in the Ioc container

Disadvantages of No.6 IOC container

Not to mention the advantages that IOC brings to us, let's take a look at the following points for attention:

The generation of objects becomes complicated by introducing a third-party IOC container in the project.

Because IOC containers generate objects through reflection, there will be some performance loss.

When using Spring's IOC container, you need to configure a large number of configuration files.

Postscript

In order to help the majority of SpringBoot users to "know what it is, but also need to know why", the author will deeply analyze the SpringBoot2.0.0.RELEASE version through a series of SpringBoot articles, so that you can have a deep understanding of its internal working principle.

List of historical articles in this series

1. [SpringBoot] use SpringBoot to quickly build and start the project

2. [SpringBoot] explain the startup process of SpringBoot application in detail

3. [SpringBoot] in-depth analysis of the application type identification mechanism of SpringBoot

4. [SpringBoot] analyze the Spring Factories mechanism in SpringBoot deeply and simply.

5. [SpringBoot] explain in detail the first three steps of the run method of SpringApplication in SpringBoot

6. [SpringBoot] illustrate the Environment mechanism of Spring

7. [SpringBoot] Source code parsing the construction process of SpringBoot application Environment

8. [SpringBoot] Banner mechanism of source code parsing SpringBoot

9. [SpringBoot] illustrate the application context mechanism of SpringBoot

10. [SpringBoot] Source code analysis of the exception handling mechanism of SpringBoot

11. [SpringBoot] Source code parses the refresh processing of SpringBoot application context

12. [SpringBoot] Source code parsing SpringBoot application context pre-processing

13. [SpringBoot] illustrate the Context of the core components of Spring

14. [SpringBoot] explain in detail the AOP of the core idea of Spring

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

Internet Technology

Wechat

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

12
Report