gpt4 book ai didi

java - @Autowired在Spring中是如何实现的

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:08:30 25 4
gpt4 key购买 nike

我真的很想对@autowired 有一个基本的了解在 Spring 中实现。
反射应该以某种方式隐含在它的实现中,但我不知道如何。
你能帮我吗 ?

最佳答案

通过@Autowired 的 Autowiring 由BeanPostProcessor 实现执行,特别是org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor .

BeanPostProcessor 处理每个 bean,将扫描其类(和父类(super class))以查找任何 @Autowired 注释,并且根据注释是什么(构造函数、字段、或方法),它将采取适当的行动。

对于构造函数

Only one constructor (at max) of any given bean class may carry this annotation with the 'required' parameter set to true, indicating the constructor to autowire when used as a Spring bean. If multiple non-required constructors carry the annotation, they will be considered as candidates for autowiring. The constructor with the greatest number of dependencies that can be satisfied by matching beans in the Spring container will be chosen. If none of the candidates can be satisfied, then a default constructor (if present) will be used. An annotated constructor does not have to be public.

对于字段

Fields are injected right after construction of a bean, before any config methods are invoked. Such a config field does not have to be public.

对于方法

Config methods may have an arbitrary name and any number of arguments; each of those arguments will be autowired with a matching bean in the Spring container. Bean property setter methods are effectively just a special case of such a general config method. Config methods do not have to be public.

所有这些都是通过反射完成的。

进一步阅读:

关于java - @Autowired在Spring中是如何实现的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31211052/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com