package com.fufan.mtsaas.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

@Component
@Lazy(value = false)
public class SpringContextUtil implements ApplicationContextAware {
  //  public class SpringContextUtil {
  public static ApplicationContext APPLICATION_CONTEXT;

  /*
   * 实现了ApplicationContextAware 接口，必须实现该方法；
   * 通过传递applicationContext参数初始化成员变量applicationContext
   */
  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    SpringContextUtil.APPLICATION_CONTEXT = applicationContext;
  }

  public static ApplicationContext getApplicationContext() {
    return APPLICATION_CONTEXT;
  }

  @SuppressWarnings("unchecked")
  public static <T> T getBean(String name) throws BeansException {
    return (T) APPLICATION_CONTEXT.getBean(name);
  }

  public static <T> T getBean(Class<T> clazz) throws BeansException {
    return (T) APPLICATION_CONTEXT.getBean(clazz);
  }
}
