package com.huigou.util;

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

import java.util.Collection;

/**
 * spring 环境包装类
 *
 * @author xx
 */
@Component
public class ApplicationContextWrapper implements ApplicationContextAware {

    private static ApplicationContext applicationContext;


    public void setApplicationContext(ApplicationContext context) {
        ApplicationContextWrapper.applicationContext = context;
    }

    public ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    @Deprecated
    public synchronized static void init(ApplicationContext context) {
        if (context != null) {
            ApplicationContextWrapper.applicationContext = context;
        }
    }

    public static ApplicationContext getContext() {
        return applicationContext;
    }

    public static Object getBean(String beanName) {
        if (applicationContext == null) {
            return null;
        }
        return applicationContext.getBean(beanName);
    }

    /**
     * 根据服务器上下文获取 Spring 管理的bean
     *
     * @param name
     * @param type
     * @return
     */
    public static <T> T getBean(String name, Class<T> type) {
        if (applicationContext == null) {
            return null;
        }
        return applicationContext.getBean(name, type);
    }

    /**
     * @since 1.1.3
     */
    public static <T> T getBean(Class<T> type) {
        if (applicationContext == null) {
            return null;
        }
        return applicationContext.getBean(type);
    }

    /**
     * @since 1.2.0
     */
    public static <T> Collection<T> getBeans(Class<T> type) {
        if (applicationContext == null) {
            return null;
        }
        return applicationContext.getBeansOfType(type).values();
    }
}
