package cn.com.countrygarden.bi.main.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

@Component
@Lazy(false)
public class SpringApplicationContext implements ApplicationContextAware {

	public static final Logger log = LoggerFactory.getLogger(SpringApplicationContext.class);

	protected static ApplicationContext appContext;

	/**
	 * SPRING AUTO INVOKE
	 */
	public void setApplicationContext(ApplicationContext applicationContext) {

		appContext = applicationContext;
	}

	/**
	 * 如果BeanFactory包含一个与所给名称匹配的bean定义，则返回true
	 * 
	 * @param name
	 * @return boolean
	 */
	public static boolean containsBean(String name) {
		return appContext.containsBean(name);
	}

	/**
	 * 判断以给定名字注册的bean定义是一个singleton还是一个prototype。
	 * 如果与给定名字相应的bean定义没有被找到，将会抛出一个异常（NoSuchBeanDefinitionException）
	 * 
	 * @param name
	 * @return boolean
	 * @throws NoSuchBeanDefinitionException
	 */
	public static boolean isSingleton(String name) throws Exception {
		return appContext.isSingleton(name);
	}

	/***
	 * 类似于getBean(String name)只是在参数中提供了需要返回到的类型。
	 * 
	 * @param name
	 * @param requiredType
	 * @return
	 * @throws BeansException
	 */
	public static <T> T getBean(String name, Class<T> requiredType) throws BeansException {
		return appContext.getBean(name, requiredType);
	}

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

	
	public static ApplicationContext getStaticApplicationContext() {
		return appContext;
	}
	
	
}
