获取Spring上下文

Spring的框架图如下:

获取Spring上下文_第1张图片

在框架图中,spring上下文贯穿整个spring框架。有时候需要手动控制Spring DI

@Component
public class SpringContext implements  ApplicationContextAware,DisposableBean{
	
	    private static ApplicationContext applicationContext;
	    /**
	     * 取得存储在静态变量中的ApplicationContext.
	     */
	    @Override
	    public void setApplicationContext(ApplicationContext context)
	            throws BeansException {
	        try {
	            applicationContext=context;
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	    }
	    /**
	     * 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
	     */
	    public static  T getBean(String name){
	        return (T) applicationContext.getBean(name);
	    }
	    public static String[] getBeanNamesForType(Class type){
	        return applicationContext.getBeanNamesForType(type);
	    }
	    /**
	     * 实现DisposableBean接口, 在Context关闭时清理静态变量.
	     */
	    @Override
	    public void destroy() throws Exception {
	        applicationContext = null;
	    }

}

你可能感兴趣的:(获取Spring上下文)