当前位置:网站首页>@Implementation principle of Autowired annotation
@Implementation principle of Autowired annotation
2022-07-25 08:20:00 【F_ five hundred and forty-nine million three hundred and twenty】
Catalog
One 、@Autowired Use of annotations
Two 、@Autowired Annotate the process of automatic assembly
3、 ... and 、@Autowired Annotation source code analysis
Preface
Before analyzing the implementation principle of this annotation , Let's review @Autowired Use of annotations .
One 、@Autowired Use of annotations
[email protected] Annotations apply to construction methods , Examples are as follows :
@Autowired
public OrderService(UserService userService){
this.userService = userService;
}@Autowired When added to the construction method ,Spring At the stage of inferring the construction method , Select this construction method to instantiate , Before reflection calls the constructor , First, according to the parameter type of the construction method 、 The parameter name is from Spring Found in the container Bean object , As a constructor .
[email protected] Annotations apply to attributes , Examples are as follows :
@Autowired
private IUserService Service;@Autowired Add to an attribute ,Spring It's going on Bean During the life cycle of , In the step of property filling , Based on the instantiated object , Added... To the object @Autowired Automatically assign a value to the property of .Spring We will go first according to the type Spring Find all... Of this type in the container Bean object , If you find more than one , Then determine another one from multiple according to the name of the attribute , If required The attribute is true, And the object cannot be found according to the attribute information , Throw the exception directly .
[email protected] Annotations apply to methods , Examples are as follows :
@Autowired
public void setUserService(UserService userService){
this.userService = userService;
}@Autowired When an annotation is written on a method ,Spring stay Bean The attribute filling phase of the lifecycle , According to the parameter type of the method 、 The parameter name is from Spring The container finds the object as a method input , Automatic reflection calls this method .
Two 、@Autowired Annotate the process of automatic assembly
@Autowired adopt Bean The post processor of
1. Creating a Spring The context is registered in the constructor AutowiredAnnotationBeanPostProcessor
2. stay Bean During the creation of :
2.1 Pre parse ( analysis @Autowired The properties of the annotation 、 Method , such as : Put the type of attribute 、 name 、 The class of the property ... Metadata is cached ;
2.2 Inject real parsing into attributes ( Get the metadata cached in the previous step IOC Container to find , And return to inject );
a. First, get the type according to the pre parsed metadata and search in the container :
· If there is no matching class in the query result , Then an exception will be reported NoSuchBeanDefinitionException
· If the query result is exactly one , It's time to bean Assemble to @Autowired Specified data ;
· If there is more than one query result , that @Autowired Will look up... By name , If not, an error will be reported NoUniqueBeanDefinitionException
3、 ... and 、@Autowired Annotation source code analysis
stay Spring In the source code ,Autowired The annotation is located in the package org.springframework.beans.factory.annotation In , The contents of the package are as follows :

Through the analysis of , It's not hard to find out Spring Yes autowired The implementation logic of annotations is located in class AutowiredAnnotationBeanPostProcessor In , It has been marked red in the figure above . The core processing code is as follows :
public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class<?> beanType, String beanName) {
InjectionMetadata metadata = this.findAutowiringMetadata(beanName, beanType, (PropertyValues)null);
metadata.checkConfigMembers(beanDefinition);
}postProcessMergedBeanDefinition() The function of the method is to find the elements that need to be automatically assembled , Build metadata information , Then encapsulate the AutowiredFieledElement or AutowiredMethodElement in , Then call the inject Method , By reflection , Calling the container's getBean() Method to find what needs to be injected Bean object , Then inject into Bean in .
protected void inject(Object bean, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
if (!this.checkPropertySkipping(pvs)) {
Method method = (Method)this.member;
Object[] arguments;
if (this.cached) {
try {
arguments = this.resolveCachedArguments(beanName);
} catch (NoSuchBeanDefinitionException var8) {
arguments = this.resolveMethodArguments(method, bean, beanName);
}
} else {
arguments = this.resolveMethodArguments(method, bean, beanName);
}
if (arguments != null) {
try {
ReflectionUtils.makeAccessible(method);
method.invoke(bean, arguments);
} catch (InvocationTargetException var7) {
throw var7.getTargetException();
}
}
}
}
边栏推荐
- Idea starts the project slowly
- Summary of SQL skills in data warehouse development
- Test the mock data method of knowing and knowing
- Science: listening to music can really relieve pain. Chinese scientists reveal the neural mechanism behind it
- CentOS 8.2 MySQL installation (xshell6)
- 刷题《剑指Offer》day02
- 第3章业务功能开发(实现全选按钮实时的响应)
- [dark horse programmer] redis learning notes 005: enterprise level solutions
- One of C language multithreading programming
- Raspberry pie 3b ffmpeg RTMP streaming
猜你喜欢

Use of lambdaquerywrapper, lambdaupdatewrapper, lambdaquerychainwrapper

Teach you to understand the computer optometry sheet

Supplementary notes on Relevant Issues of complete model group
![[dark horse programmer] redis learning notes 005: enterprise level solutions](/img/76/959d18994ab9eb170cbdbdccbe94e7.png)
[dark horse programmer] redis learning notes 005: enterprise level solutions

Advanced C language (XIII) - Example Analysis of dynamic memory management

【黑马程序员】Redis学习笔记005:企业级解决方案

Node+js build time server

Hotel room management system based on jsp+servlet+mysql

Redis最佳实践

JS cool rolling picture deformation animation JS special effects
随机推荐
【黑马程序员】Redis学习笔记002:持久化:RDB 和 AOF
Redis learning
华为设备远程登录(Telnet、SSH)配置
Can Flink's current capabilities support the synchronization of a table from source (MySQL) to sink (MySQL) to separate databases and tables
In depth analysis of yolov7 network architecture
CAS操作
Redis最佳实践
JVM specification Oracle official website
Svg creative underline style JS special effect
"Unable to recognize" yarn "item as cmdlet, function, script file
Surpassing transformer, Tsinghua, byte significantly refresh parallel text generation SOTA performance | ICML 2022
机器学习理论及案例分析(part2)--回归
Advanced C language (XII) - dynamic memory management
Check the computer restart times and reasons
Message Oriented Middleware
Source code of pet adoption management system implemented by ssm+jsp+mysql
一款强大的端口扫描工具(nmap)
Redis core principles
Online shopping E-commerce mall system based on jsp+servlet+mysql+
Raspberrypico serial communication