spring autowiring not working from a non-spring managed class

前端 未结 10 905
暗喜
暗喜 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);
    

提交回复
热议问题