Spring get current ApplicationContext

后端 未结 11 928
陌清茗
陌清茗 2020-11-28 20:04

I am using Spring MVC for my web application. My beans are written in \"spring-servlet.xml\" file

Now I have a class MyClass and i want to

11条回答
  •  臣服心动
    2020-11-28 20:56

    In case you need to access the context from within a HttpServlet which itself is not instantiated by Spring (and therefore neither @Autowire nor ApplicationContextAware will work)...

    WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
    

    or

    SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
    

    As for some of the other replies, think twice before you do this:

    new ClassPathXmlApplicationContext("..."); // are you sure?
    

    ...as this does not give you the current context, rather it creates another instance of it for you. Which means 1) significant chunk of memory and 2) beans are not shared among these two application contexts.

提交回复
热议问题