package org.xyzh.common.utils.spring;

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

/**
 * @description Spring上下文工具类 - 用于在非Spring管理的类中获取Bean
 * @filename SpringContextUtil.java
 * @author yslg
 * @copyright xyzh
 * @since 2025-10-30
 */
@Component
public class SpringContextUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

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

    /**
     * @description 获取Spring容器中的Bean
     * @param beanClass Bean的Class类型
     * @return T Bean实例
     */
    public static <T> T getBean(Class<T> beanClass) {
        if (applicationContext == null) {
            return null;
        }
        try {
            return applicationContext.getBean(beanClass);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * @description 获取Spring容器中的Bean
     * @param beanName Bean的名称
     * @return Object Bean实例
     */
    public static Object getBean(String beanName) {
        if (applicationContext == null) {
            return null;
        }
        try {
            return applicationContext.getBean(beanName);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * @description 获取ApplicationContext
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
}

