package com.mosty.common.base.util;

import org.springframework.aop.framework.AopContext;
import org.springframework.boot.SpringApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.util.Map;

/**
 *  Bean ioc 静态工具类
 * @author kevin
 * @date 2020/9/17 13:21
 * @since 1.0.0
 */
@Component
@SuppressWarnings("unused")
public class SpringIocContext implements ApplicationContextAware {

    /**
     * spring IOC容器
     * @see SpringApplication #createApplicationContext()
     */
    public static ApplicationContext applicationContext;

    public SpringIocContext() {
    }

    @Override
    public void setApplicationContext(@NonNull ApplicationContext applicationContext) {
        SpringIocContext.applicationContext = applicationContext;
    }

    /**
     * 获取带有 注解的类
     * @param annotationClass 注解类
     * @return 标注了注解的Bean
     */
    public static Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annotationClass) {
        try {
            return applicationContext.getBeansWithAnnotation(annotationClass);
        } catch (Exception var2) {
            return null;
        }
    }

    /**
     * 从ioc容器获取bean
     * @param beanClass bean {@link Class}
     * @param <T> 泛型
     * @return bean对象
     */
    public static <T> T getBean(Class<T> beanClass) {
        return applicationContext.getBean(beanClass);
    }

    /**
     * 从ioc容器获取bean
     * @param beanName bean名称
     * @return bean对象
     */
    public static Object getBean(String beanName) {
        return applicationContext.getBean(beanName);
    }

    /**
     * 获取aop代理对象
     *
     * @param invoker
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T getAopProxy(T invoker)
    {
        return (T) AopContext.currentProxy();
    }

}
