Can you use @Autowired with static fields?

后端 未结 11 1608
臣服心动
臣服心动 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:42

    You can use ApplicationContextAware

    @Component
    public class AppContext implements ApplicationContextAware{
        public static ApplicationContext applicationContext;
    
        public AppBeans(){
        }
    
        @Override
        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            this.applicationContext = applicationContext;
        }
    }
    

    then

    static ABean bean = AppContext.applicationContext.getBean("aBean",ABean.class);
    

提交回复
热议问题