package com.wecloud.im.ws.utils;

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

import java.util.Collection;
import java.util.List;

/**
 * @Description 在非spring管理的类中获取spring注册的bean
 * @Author hewei hwei1233@163.com
 * @Date 2020-01-03
 */
@Component
public class SpringBeanUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    public static Object getBean(String name) {
        return applicationContext.getBean(name);
    }

    public static <T> T getBean(Class<T> clazz) {
        return applicationContext.getBean(clazz);
    }

    public static <T> Collection<T> getBeansOfType(Class<T> clazz) {
        return applicationContext.getBeansOfType(clazz).values();
    }

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {

        if (context != null) {
            applicationContext = context;
        }

    }
}
