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 the principle of springBoot automatic injection

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

Share

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

This article shares with you the content of a sample analysis of the principle of springBoot automatic injection. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

@ SpringBootApplication Annotation interpretation

Why our startup class is marked with an @ SpringBootApplication annotation and a run () method can be run, you can see how powerful our @ SpringBootApplication annotation is.

@ SpringBootApplicationpublic class App {public static void main (String [] args) {SpringApplication.run (App.class, args);}}

@ SpringBootApplication is actually composed of three-word annotations. We can completely replace @ SpringBootApplication with these three annotations.

@ SpringBootConfiguration@EnableAutoConfiguration@ComponentScan (excludeFilters = {@ ComponentScan.Filter (type = FilterType.CUSTOM, classes = TypeExcludeFilter.class), @ ComponentScan.Filter (type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class)}) public class App {public static void main (String [] args) {SpringApplication.run (App.class, args);}}

Let's talk about the role of these three annotations, what they have done, and why only a few annotations can make our program run.

1.@SpringBootConfiguration

In fact, click into it is a @ Configuration, nothing special, friends who have studied spring know that this is used to mark a configuration class.

2.@EnableAutoConfiguration

The key point is the @ EnableAutoConfiguration annotation. Let's take a look at one of its components.

@ Target (ElementType.TYPE) @ Retention (RetentionPolicy.RUNTIME) @ Documented@Inherited@AutoConfigurationPackage@Import (AutoConfigurationImportSelector.class) public @ interface EnableAutoConfiguration {@ Inherited

@ Inherited: if this annotation indicates that subclasses can also be inherited, this is not very important.

Let's first take a look at the @ AutoConfigurationPackage annotation in the @ EnableAutoConfiguration annotation. What is it? You can see that a component of type AutoConfigurationPackages.Registrar has been imported

@ AutoConfigurationPackage

@ AutoConfigurationPackage:

@ Target (ElementType.TYPE) @ Retention (RetentionPolicy.RUNTIME) @ Documented@Inherited@Import (AutoConfigurationPackages.Registrar.class) public @ interface AutoConfigurationPackage {

Let's take a look at what the imported AutoConfigurationPackages.Registrar component does.

RegisterBeanDefinitions? Is registerBeanDefinitions adding components to our container? Let's take a look at the specific components he imported. You can hit the breakpoint on these two methods.

Static class Registrar implements ImportBeanDefinitionRegistrar, DeterminableImports {@ Override public void registerBeanDefinitions (AnnotationMetadata metadata, BeanDefinitionRegistry registry) {register (registry, new PackageImports (metadata). GetPackageNames (). ToArray (new String [0]));} @ Override public Set determineImports (AnnotationMetadata metadata) {return Collections.singleton (new PackageImports (metadata)) }}

As long as we register the BeanDefinition, we only need to call getBean () to get the object. Of course, we don't have to call it ourselves. When spring finally refreshes the container at the bottom, it initializes all single-instance bean, which is why we can get the original of the object directly by using the relevant annotations.

GetBean () has two meanings:

1. In the container, it is obtained directly from the cache

two。 One is not created directly in the container, that is, it is created in the lifecycle of bean.

AutoConfigurationImportSelector.class

@ Import (AutoConfigurationImportSelector.class) core component, let's see what he has done.

AutoConfigurationImportSelector inherits DeferredImportSelector,DeferredImportSelector. He has an internal interface Group, and there is a method process () in Group.

So we went to the process () method in AutoConfigurationImportSelector to make a breakpoint and observe.

Override public void process (AnnotationMetadata annotationMetadata, DeferredImportSelector deferredImportSelector) {Assert.state (deferredImportSelector instanceof AutoConfigurationImportSelector, ()-> String.format ("Only% s implementations are supported, got% s", AutoConfigurationImportSelector.class.getSimpleName () DeferredImportSelector.getClass () .getName ()) AutoConfigurationEntry autoConfigurationEntry = ((AutoConfigurationImportSelector) deferredImportSelector) .getAutoConfigurationEntry (annotationMetadata); this.autoConfigurationEntries.add (autoConfigurationEntry); for (String importClassName: autoConfigurationEntry.getConfigurations ()) {this.entries.putIfAbsent (importClassName, annotationMetadata) }}

As soon as this method comes up, it needs to get some automatically injected entry autoConfigurationEntry, so let's take a look at how he got it, and what exactly did he get?

From the stack information, we can see that it is called through the invokeBeanDefinitionRegistryPostProcessors () method, indicating that after the factory is initialized, you can throw some bean definition information into it.

That's the way to get in.

Protected AutoConfigurationEntry getAutoConfigurationEntry (AnnotationMetadata annotationMetadata) {if (! isEnabled (annotationMetadata)) {return EMPTY_ENTRY;} AnnotationAttributes attributes = getAttributes (annotationMetadata); List configurations = getCandidateConfigurations (annotationMetadata, attributes); configurations = removeDuplicates (configurations); Set exclusions = getExclusions (annotationMetadata, attributes) CheckExcludedClasses (configurations, exclusions); configurations.removeAll (exclusions); configurations = getConfigurationClassFilter (). Filter (configurations); fireAutoConfigurationImportEvents (configurations, exclusions); return new AutoConfigurationEntry (configurations, exclusions);}

Let's re-enter this method.

In the loadFactoryNames () method

Then let's go and see what's in this file.

Combined with the above code, whether he wants to load the contents of org.springframework.boot.autoconfigure.EnableAutoConfiguration or not, these are some configuration class information.

In fact, the name of the permission of each class in this file spring.factories is a configuration class, but springBoot has written all these configuration classes and injected them directly into you when we need them in some scenarios, which explains why we don't have to write so many configuration files.

I randomly click on a class to take a look at it.

After loading: how much? Do you need all of them?

You see the following code, whether to exclude, remove, filter out some, ah, exclusion is our own exclusion attributes written in the comments to exclude, so that after a series of filtering.

Finally, put this information into entries.

3.@ComponentScan

The function of the @ ComponentScan annotation is to scan all the classes on the current class that mark the package path of this annotation, which is why we need to put the main startup class on the outermost original. If you want to put the configuration class somewhere else, you have to manually specify the package scan path.

Thank you for reading! This is the end of this article on "sample analysis of the principle of springBoot automatic injection". 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 out 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