Spring,通过ApplicationContextAware获取ApplicationContext

import java.util.Map;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;


@Component
public class ApplicationContextFactory implements ApplicationContextAware {


    private static ApplicationContext applicationContext;


    public void setApplicationContext(ApplicationContext applicationContext) {
        ApplicationContextFactory.applicationContext = applicationContext;
    }


    public static ApplicationContext getApplicationContext() {
        checkApplicationContext();
        return applicationContext;
    }


    @SuppressWarnings("unchecked")
    public static  T getBean(String name) {
        checkApplicationContext();
        return (T) applicationContext.getBean(name);
    }


    public static  Map getBeansOfType(Class clazz) {
        checkApplicationContext();
        return applicationContext.getBeansOfType(clazz);
    }

    public static  T getBean(Class clazz) {
        checkApplicationContext();
        return applicationContext.getBean(clazz);
    }


    public static void cleanApplicationContext() {
        applicationContext = null;
    }


    private static void checkApplicationContext() {
        if (applicationContext == null) {
            throw new IllegalStateException("applicaitonContext not injected");
        }
    }
}

你可能感兴趣的:(spring)