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

How to write the IoC source code in Spring

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

Share

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

This article is to share with you about how to write the IoC source code in Spring, the editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.

1. IoC theory

The full name of IoC is Inversion of Control, translated as "control inversion", and it also has an alias DI (Dependency Injection), which is dependency injection.

II. IoC mode

Spring provides two ways for IoC, one is based on xml, the other is based on annotations.

Tag to define the bean and manage it.

The @ Bean annotation defines the bean for management.

In this article, we will analyze the principle of IoC based on annotations. We can bring some questions before reading the article, which will help us to understand it better.

What is @ Bean for?

What do @ Controller and @ Service do?

How does the @ CompoentScan annotation work?

How did Spring find annotated classes like @ Bean, @ Controller, @ Service?

How did you register in the IOC container after discovery?

What on earth is an IOC container?

III. Source code analysis

First, take a look at the following code:

AnnotationConfigApplicationContext aac = new AnnotationConfigApplicationContext ("com.mydemo")

AnnotationConfigApplicationContext enables Java-based configuration classes (including various annotations) to load the application context of Spring. Avoid using application.xml for configuration. Compared with XML configuration, it is more convenient.

3.1. Class structure diagram

Main class or interface description:

The GenericApplicationContext-- generic application context holds an DefaultListableBeanFactory instance internally. This class implements the BeanDefinitionRegistry interface and can use any bean definition reader on it. A typical use case is to register bean definitions through the BeanFactoryRegistry interface, then call the refresh () method to initialize bean with application context semantics (org.springframework.context.ApplicationContextAware), automatically detect org.springframework.beans.factory.config.BeanFactoryPostProcessor, and so on.

BeanDefinitionRegistry-- is used to hold the registry interface of bean definitions like RootBeanDefinition and ChildBeanDefinition instances. DefaultListableBeanFactory implements this interface, so you can register bean with beanFactory through the appropriate method. GenericApplicationContext has a built-in DefaultListableBeanFactory instance, and its implementation of this interface is actually achieved by calling the corresponding method of the instance.

The abstract implementation of the AbstractApplicationContext--ApplicationContext interface does not enforce the configured storage type, but only implements the general context function. This implementation uses the template method design pattern and requires specific subclasses to implement its abstract methods. Automatically registers BeanFactoryPostProcessor through the registerBeanPostProcessors () method. The examples of BeanPostProcessor and ApplicationListener are used to detect special bean-- in bean factory. Comparison 1 Analysis

AnnotationConfigRegistry-- annotations configure the registry. A generic interface for annotating the configuration application context, with a method to register configuration classes and scan configuration classes.

3.2Constructor / / default constructor initializes an empty container that does not contain any Bean information. You need to register the configuration class later by calling its register () / / method, and call the refresh () method to refresh the container, triggering the container to load, parse and register the annotated Bean public AnnotationConfigApplicationContext () {this.reader = new AnnotatedBeanDefinitionReader (this) This.scanner = new ClassPathBeanDefinitionScanner (this);} public AnnotationConfigApplicationContext (DefaultListableBeanFactory beanFactory) {super (beanFactory); this.reader = new AnnotatedBeanDefinitionReader (this); this.scanner = new ClassPathBeanDefinitionScanner (this) } / / the most commonly used constructor that automatically registers the Bean in the corresponding configuration class with the container public AnnotationConfigApplicationContext (Class...) by passing the configuration class involved to the constructor AnnotatedClasses) {/ / call the no-parameter constructor to initialize AnnotatedBeanDefinitionReader and ClassPathBeanDefinitionScanner this (); register (annotatedClasses); refresh () } / / this constructor automatically scans all classes under the given package and its subpackages, automatically identifies all Spring Bean, and registers them with the container public AnnotationConfigApplicationContext (String... BasePackages) {/ / initialize ClassPathBeanDefinitionScanner and AnnotatedBeanDefinitionReader this (); / / step1 / / scan packages, register bean scan (basePackages); / / step2 refresh (); / / step3}

Main attributes:

The AnnotatedBeanDefinitionReader--BeanDefinition parser is used to parse annotated bean

ClassPathBeanDefinitionScanner--bean 's scanner is used to scan classes

Register to parse incoming configuration classes (parsing using class configuration)

Initialize the container by calling the container's refresh method

Here we use the last constructor, which passes in a package path.

3.3.Constructor initialization of IoC

First, look at step1, which calls the no-parameter constructor of this class:

Public AnnotationConfigApplicationContext () {this.reader = new AnnotatedBeanDefinitionReader (this); this.scanner = new ClassPathBeanDefinitionScanner (this);}

Then initialize AnnotatedBeanDefinitionReader and ClassPathBeanDefinitionScanner

Let's take a look at the constructor of ClassPathBeanDefinitionScanner

Public ClassPathBeanDefinitionScanner (BeanDefinitionRegistry registry) {this (registry, true);}

Continue to trace, and finally call this method:

Public ClassPathBeanDefinitionScanner (BeanDefinitionRegistry registry, boolean useDefaultFilters, Environment environment, @ Nullable ResourceLoader resourceLoader) {Assert.notNull (registry, "BeanDefinitionRegistry must not be null"); / / load the registry defined by Bean for the container this.registry = registry / / whether to use the default filtering rule if (useDefaultFilters) {registerDefaultFilters ();} / set environment setEnvironment (environment); / / set resource loader setResourceLoader (resourceLoader) for the container;}

The most important of these is the registerDefaultFilters () method, which initializes the default filtering rules for spring scanning, corresponding to the @ ComponentScan annotation, and initializes the default filtering rules if there are no custom rules.

The registerDefaultFilters () method in the ClassPathScanningCandidateComponentProvider class is called here:

/ / register filter rules @ SuppressWarnings ("unchecked") protected void registerDefaultFilters () {/ / add @ Component annotation classes / / @ Service and @ Controller to the filter rules to be included are Component, because these annotations add @ Component annotation this.includeFilters.add (new AnnotationTypeFilter (Component.class)); / / get the class loader ClassLoader cl = ClassPathScanningCandidateComponentProvider.class.getClassLoader () of the current class Try {/ / add JavaEE6's @ ManagedBean annotation this.includeFilters.add (new AnnotationTypeFilter ((Class)) to the filter rule to be included

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