package com.usoftchina.bi.core.utils;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;

public class ContextUtil {
	private static ApplicationContext applicationContext;
	public static void setApplicationContext(ApplicationContext applicationContext) {
		synchronized (ContextUtil.class) {
			ContextUtil.applicationContext = applicationContext;
			ContextUtil.class.notifyAll();
		}
	}

	public static ApplicationContext getApplicationContext() {
		synchronized (ContextUtil.class) {
			while (applicationContext == null) {
				try {
					ContextUtil.class.wait(6000);
				} catch (InterruptedException ex) {
				}
			}
			return applicationContext;
		}
	}

	/**
	 * 获取bean
	 *
	 * @param name
	 * @return
	 */
	public static Object getBean(String name) {
		try {
			return getApplicationContext().getBean(name);
		} catch (Exception e) {
			return null;
		}

	}

	/**
	 * 获取bean
	 *
	 * @param cls
	 * @return
	 */
	public static <T> T getBean(Class<T> cls) {
		return getApplicationContext().getBean(cls);
	}


	/**
	 * 触发事件
	 *
	 * @param event
	 */
	public static void publishEvent(ApplicationEvent event) {
		getApplicationContext().publishEvent(event);
	}

}
