package com.inspect.client.service;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class SpringApplicationContext implements ApplicationContextAware {
   private static ApplicationContext applicationContext;

   public void setApplicationContext(ApplicationContext applicationContext) {
      applicationContext = applicationContext;
   }

   public static ApplicationContext getApplicationContext() {
      checkApplicationContext();
      return applicationContext;
   }

   public static <T> T getBean(String name) {
      checkApplicationContext();
      return (T) applicationContext.getBean(name);
   }

   public static <T> Map<String, T> getBean(Class<T> clazz) {
      checkApplicationContext();
      return applicationContext.getBeansOfType(clazz);
   }

   public static void cleanApplicationContext() {
      applicationContext = null;
   }

   private static void checkApplicationContext() {
      if(applicationContext == null) {
         throw new IllegalStateException("applicaitonContext未注入,请在spring的context.xml中定义SpringContextHolder");
      }
   }
}
