Can you use @Autowired with static fields?

后端 未结 11 1353
臣服心动
臣服心动 2020-11-22 13:15

Is there some way to use @Autowired with static fields. If not, are there some other ways to do this?

11条回答
  •  清酒与你
    2020-11-22 13:34

    Init your autowired component in @PostConstruct method

    @Component
    public class TestClass {
       private static AutowiredTypeComponent component;
    
       @Autowired
       private AutowiredTypeComponent autowiredComponent;
    
       @PostConstruct
       private void init() {
          component = this.autowiredComponent;
       }
    
       public static void testMethod() {
          component.callTestMethod();
       }
    }
    

提交回复
热议问题