Springs.java 1.51 KB
package org.nafmii.response;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

/**
 * @author lvyp
 * @date 2021/4/26
 */
@Component
public class Springs implements ApplicationListener {
    @Autowired
    private ApplicationContext applicationContext;
    private static ApplicationContext context;

    public Springs() {
    }

    public void onApplicationEvent(ApplicationEvent applicationEvent) {
        if (applicationEvent instanceof ContextRefreshedEvent) {
            this.setContextStatic();
        }

    }

    private synchronized void setContextStatic() {
        context = this.applicationContext;
    }

    public static <T> T getBean(Class<? extends T> beanClass, String beanName) {
        assertContextNotNull();
        return context.getBean(beanName, beanClass);
    }

    public static Object getBean(String beanName) {
        assertContextNotNull();
        return context.getBean(beanName);
    }

    public static <T> T getBean(Class<? extends T> beanClass) {
        assertContextNotNull();
        return context.getBean(beanClass);
    }

    private static void assertContextNotNull() {
        Assert.notNull(context, "The spring applicationContext was not initialized");
    }
}