package com.zm.order.tool.server.utils;

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

/**
 * <p>
 *
 * </p>
 *
 * @author nianchang
 * @date 2024/02/22 5:37 下午
 */
@Component
public class SpringContextUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

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

    /**
     * 获取指定Bean对象（类型）
     *
     * <p>
     *
     * </p>
     *
     * @param clz Class
     *
     * @return bean
     */
    public static <T> T getBean(Class<T> clz) throws BeansException {
        return applicationContext.getBean(clz);
    }

    /**
     * 获取指定Bean对象（名称）
     *
     * <p>
     *
     * </p>
     *
     * @param name bean name
     *
     * @return Class 注册对象的类型
     * @throws NoSuchBeanDefinitionException Bean不存在异常
     */
    public static Class<?> getType(String name) throws NoSuchBeanDefinitionException {
        return applicationContext.getType(name);
    }
}
