zoukankan      html  css  js  c++  java
  • Spring Boot @Component注解下的类 @Autowired 为null

    Spring Boot @Component注解下的类 @Autowired 为null【原文

      @Component
            public class ComponentClass {
    
          @Autowired
          private JedisClient jedisClient;
          public static ComponentClass componentClass;
          @PostConstruct
          public void init(){
              componentClass = this;
              componentClass.jedisClient = this.jedisClient;
          }
      }
      // 后续使用 componentClass.jedisClient.**()
    

    没注入成功,或者说是此类在bean加载之前就被调用了。
    声明一个此类的静态变量,用以保存bean。
    使用@PostConstruct注解,将需要注入的类添加到静态变量中。
    接下来,使用这个静态变量来调用注入类就行了。
    @PostConstruct这个注解的具体作用就是:

    注解在方法上,表示此方法是在Spring实例化该bean之后马上执行此方法,之后才会去实例化其他bean。

    这样在Spring实例化ComponentClass之后,马上执行此方法,初始化ComponentClass静态对象和成员变量jedisClient。

    spring中Constructor、@Autowired、@PostConstruct的顺序 【原文

    其实从依赖注入的字面意思就可以知道,要将对象p注入到对象a,那么首先就必须得生成对象p与对象a,才能执行注入。所以,如果一个类A中有个成员变量p被@Autowired注解,那么@Autowired注入是发生在A的构造方法执行完之后的。

    如果想在生成对象时候完成某些初始化操作,而偏偏这些初始化操作又依赖于依赖注入,那么就无法在构造函数中实现。为此,可以使用@PostConstruct注解一个方法来完成初始化,@PostConstruct注解的方法将会在依赖注入完成后被自动调用。

    Constructor >> @Autowired >> @PostConstruct

        public Class AAA {
            @Autowired
            private BBB b;
    
            public AAA() {
                System.out.println("此时b还未被注入: b = " + b);
            }
    
            @PostConstruct
            private void init() {
                System.out.println("@PostConstruct将在依赖注入完成后被自动调用: b = " + b);
            }
        }
  • 相关阅读:
    LeetCode "Palindrome Partition II"
    LeetCode "Longest Substring Without Repeating Characters"
    LeetCode "Wildcard Matching"
    LeetCode "Best Time to Buy and Sell Stock II"
    LeetCodeEPI "Best Time to Buy and Sell Stock"
    LeetCode "Substring with Concatenation of All Words"
    LeetCode "Word Break II"
    LeetCode "Word Break"
    Some thoughts..
    LeetCode "Longest Valid Parentheses"
  • 原文地址:https://www.cnblogs.com/cuiyf/p/13665733.html
Copyright © 2011-2022 走看看