package cn.com.qmth.examcloud.core.questions.base;

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

import java.util.Map;

/**
 * 获取ApplicationContext和Object的工具类
 */
@Component
public class SpringContextUtils implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    public void setApplicationContext(ApplicationContext arg0) throws BeansException {
        applicationContext = arg0;
    }

    /**
     * 获取applicationContext对象
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 获取Bean
     */
    public static Object getBeanById(String id) {
        return applicationContext.getBean(id);
    }

    /**
     * 获取Bean
     */
    public static <T> T getBean(Class<T> clazz, String beanName) {
        return (T) applicationContext.getBean(beanName);
    }

    /**
     * 根据bean的class来查找对象
     */
    @SuppressWarnings({"unchecked", "rawtypes"})
    public static Object getBeanByClass(Class c) {
        return applicationContext.getBean(c);
    }

    /**
     * 根据bean的class来查找所有的对象(包括子类)
     */
    @SuppressWarnings({"unchecked", "rawtypes"})
    public static Map getBeansByClass(Class c) {
        return applicationContext.getBeansOfType(c);
    }

}
