Spring get current ApplicationContext

后端 未结 11 943
陌清茗
陌清茗 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:55

    There are many way to get application context in Spring application. Those are given bellow:

    1. Via ApplicationContextAware:

      import org.springframework.beans.BeansException;
      import org.springframework.context.ApplicationContext;
      import org.springframework.context.ApplicationContextAware;
      
      public class AppContextProvider implements ApplicationContextAware {
      
      private ApplicationContext applicationContext;
      
      @Override
      public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
          this.applicationContext = applicationContext;
      }
      }
      

    Here setApplicationContext(ApplicationContext applicationContext) method you will get the applicationContext

    1. Via Autowired:

      @Autowired
      private ApplicationContext applicationContext;
      

    Here @Autowired keyword will provide the applicationContext.

    For more info visit this thread

    Thanks :)

提交回复
热议问题