content: package com.example.demo.utils;
  
  import org.springframework.beans.BeansException;
  import org.springframework.beans.factory.DisposableBean;
  import org.springframework.context.ApplicationContext;
  import org.springframework.context.ApplicationContextAware;
  import org.springframework.context.annotation.Lazy;
  import org.springframework.stereotype.Component;
  import org.springframework.stereotype.Service;
  
  /**
   * Spring上下文获取工具
   *
   * @author 李嘉
   * @version 1.0
   * @Description Spring上下文获取工具
   * @date 2019-05-10 13:25
   */
  @Component
  public class SpringContextUtils implements ApplicationContextAware, DisposableBean {
  
      public static ApplicationContext applicationContext;
  
      /**
       * 取得存储在静态变量中的ApplicationContext.
       */
      public static ApplicationContext getApplicationContext() {
          checkApplicationContext();
          return applicationContext;
      }
  
      /**
       * 实现ApplicationContextAware接口的context注入函数, 将其存入静态变量.
       */
      @Override
      public void setApplicationContext(ApplicationContext applicationContext)
              throws BeansException {
          SpringContextUtils.applicationContext = applicationContext;
      }
  
      /**
       * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
       */
      @SuppressWarnings("unchecked")
      public static <T> T getBean(String name) {
          checkApplicationContext();
          return (T) applicationContext.getBean(name);
      }
  
      /**
       * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
       */
      public static <T> T getBean(Class<T> clazz) {
          checkApplicationContext();
          return applicationContext.getBean(clazz);
      }
  
      public static <T> T getBean(String name, Class<T> requiredType) {
          return applicationContext.getBean(name, requiredType);
      }
  
      public static boolean containsBean(String name) {
          return applicationContext.containsBean(name);
      }
  
      public static boolean isSingleton(String name) {
          return applicationContext.isSingleton(name);
      }
  
      public static Class<? extends Object> getType(String name) {
          return applicationContext.getType(name);
      }
  
  
      /**
       * 清除applicationContext静态变量.
       */
      public static void cleanApplicationContext() {
          applicationContext = null;
      }
  
      private static void checkApplicationContext() {
          if (applicationContext == null) {
              throw new IllegalStateException("applicaitonContext未注入,请在applicationContext.xml中定义SpringContextHolder");
          }
      }
  
      @Override
      public void destroy() throws Exception {
          SpringContextUtils.cleanApplicationContext();
      }
  }
  