spring autowiring not working from a non-spring managed class

前端 未结 10 889
暗喜
暗喜 2020-12-03 06:43

I have a class (Class ABC) that\'s instantiated by calling the constructor. Class ABC in turn has a helper class (Class XYZ) injected using auto-wired.

Ours is a Sp

10条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-03 07:50

    In response to the answer provided by @Ashish Chaurasia, would like to mention that the solution is partial. The class ApplicationContextUtils should also be a spring bean in order for spring to invoke the below code.

    if (bean instanceof ApplicationContextAware) {
    ((ApplicationContextAware) bean).setApplicationContext(ctx); 
    }
    

    @Component at the top of the class would make the solution complete. Also, there is one more alternative of doing it with the @Autowired annotation.

    @Component
    public class ApplicationContextProvider {
        private static ApplicationContext context;
    
        public static ApplicationContext getApplicationContext() {
            return context;
        }
    
        @Autowired
        public void setContext(ApplicationContext context) {
            ApplicationContextProvider.context = context;
        }
    }
    

    The getBean method can now easily be accessed by -

    ApplicationContextProvider.getApplicationContext().getBean("myBean");

提交回复
热议问题