package com.usoft.credit.util;

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;

/**
 * spring容器上下文对象
 * @author liuam
 * @since 2018/6/25 0025 下午 15:12
 */
public class ContextUtils {

    private static ApplicationContext applicationContext;

    private static Logger logger = Logger.getLogger(ContextUtils.class);

    public static void setApplicationContext(ApplicationContext applicationContext) {
        logger.debug("setApplicationContext, notifyAll");
        ContextUtils.applicationContext = applicationContext;
    }

    /**
     * 获取上下文对象，需容器启动才可调用
     * @return
     */
    public static ApplicationContext getApplicationContext() {
        while (applicationContext == null) {
            try {
                logger.debug("getApplicationContext, wait...");
                ContextUtils.class.wait(60000);
                if (applicationContext == null) {
                    logger.debug("Have been waiting for ApplicationContext to be set for 1 minute", new Exception());
                }
            } catch (InterruptedException ex) {
                logger.debug("getApplicationContext, wait interrupted");
            }
        }
        return applicationContext;
    }

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

    /**
     * 获取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);
    }

}
