zoukankan      html  css  js  c++  java
  • Spring框架里注解@Autowired的工作原理

    Suppose I have a bean named HelloWorld which has a member attribute points to another bean User.

    With annotation @Autowired, as long as getBean is called in the runtime, the returned HelloWorld instance will automatically have user attribute injected with User instance.

    How is this behavior implemented by Spring framework?

    (1) in Spring container implementation’s refresh method, all singleton beans will be initialized by default.

    When the HelloWorld bean is initialized:

    Since it has the following source code:

    @Autowired
    private User user;
    

    In the runtime, this annotation is available in metadata via reflection. In metadata structure below, the targetClass points to HelloWorld bean, and injectedElements points to the User class to be injected.


    (2) In doResolveDependency, the definition for User bean is searched based on this.beanDefinitionNames ( list in DefaultListableBeanFactory ):

    Once found, the found result is added to array candidateNames:

    Then the constructor of User bean class is called ( still triggered by getBean call ), the user instance is created by calling constructor:

    The created user instance together with its name “user” is inserted to the map matchingBeans.

    1. Finally the user reference is set to user attribute of HelloWorld instance via reflection. Here the variable bean in line 569 points to HelloWorld instance, and value points to user instance.

    Once field.set(bean, value) is done, we can observe in debugger that the user attribute in HelloWorld instance is already injected successfully.

    要获取更多Jerry的原创文章,请关注公众号"汪子熙":

  • 相关阅读:
    kmp 算法
    jdk 和 cglib 的动态代理
    RestTemplate工具类
    bat脚本切换多个工程的分支
    字符串的左旋转
    输入一个正数s,打印出所有和为s的连续正数序列(至少含有两个数)。例如输入15,由于1+2+3+4+5=4+5+6=7+8=15,所以结果打印出3个连续序列1~5、4~6和7~8。
    枚举类型在JPA中的使用
    拾遗
    YAML DEMO
    kiali 1.26 anonymous策略修改为token
  • 原文地址:https://www.cnblogs.com/sap-jerry/p/12844909.html
Copyright © 2011-2022 走看看