package com.trade.common.utils.bean;

import cn.hutool.core.lang.Assert;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @description:
 * @Author: wanglang
 * @Date: 2024/10/14 21:00
 * @Version: 1.0
 */
@Component
public class SpringBeanUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringBeanUtil.applicationContext = applicationContext;
    }

    /**
     * <p>
     * 根据类的clazz获取
     * <p>
     * 
     * @param clazz clazz
     * @return {@link T}
     **/
    public static <T> T getBean(Class<T> clazz) {
        T t = applicationContext != null ? applicationContext.getBean(clazz) : null;
        Assert.notNull(t, "当前Bean为空，请重新选择！");
        return t;
    }

    /**
     * <p>
     * 根据Bean名字获取
     * <p>
     * 
     * @param clazzName bean名字
     * @return {@link Object}
     **/
    public static Object getBean(String clazzName) {
        return applicationContext.getBean(clazzName);
    }
}
