spring autowiring not working from a non-spring managed class

前端 未结 10 887
暗喜
暗喜 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:43

    You can use this way to use spring bean in non-spring bean class

        public class ApplicationContextUtils implements ApplicationContextAware {
    
      private static ApplicationContext ctx;
    
      @Override
      public void setApplicationContext(ApplicationContext appContext)
          throws BeansException {
        ctx = appContext;
    
      }
    
      public static ApplicationContext getApplicationContext() {
        return ctx;
      }
    }
    

    now you can get the applicationcontext object by getApplicationContext() this method.

    from applicationcontext you can get spring bean objects like this:

     ApplicationContext appCtx = ApplicationContextUtils
        .getApplicationContext();
    String strFromContext = (String) appCtx.getBean(beanName);
    
    0 讨论(0)
  • 2020-12-03 07:47

    You can annotate ABC class with @Configurable annotation. Then Spring IOC will inject XYZ instance to ABC class. It's typically used with the AspectJ AnnotationBeanConfigurerAspect.

    0 讨论(0)
  • 2020-12-03 07:49

    Correct: You can't just call new on a class and get it all wired up; Spring has to be managing the bean for it to do all of its magic.

    If you can post more details on your use case, we may be able to suggest useful options.

    0 讨论(0)
  • 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");

    0 讨论(0)
提交回复
热议问题