package com.fs.fssync.config;

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

import java.io.Serializable;

@Component
public class SpringContextHolder implements ApplicationContextAware, Serializable {

    private static final long serialVersionUID = 1L;

    private static ApplicationContext applicationContext;

    // 记录是否已初始化
    private static volatile boolean initialized = false;

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

    public static ApplicationContext getApplicationContext() {
        if (!initialized) {
            throw new IllegalStateException("ApplicationContext has not been initialized");
        }
        return applicationContext;
    }

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

    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }
}
