一、ApplicationContext对象spring
ApplicationContext ac = new FileSystemXmlApplicationContext("applicationContext.xml"); ac.getBean("beanId");
服务器
说明:Spring框架程序经过配置文件手工初始化Spring的状况。app
二、经过Spring提供的工具类获取ApplicationContext对象框架
ApplicationContext ac1 = WebApplicationContextUtils.getRequiredWebApplicationContext(ServletContext sc); ApplicationContext ac2 = WebApplicationContextUtils.getWebApplicationContext(ServletContext sc); ac1.getBean("beanId"); ac2.getBean("beanId");
函数
说明:经过ServletContext对象获取ApplicationContext对象,而后在经过它获取须要的类实例。工具
三、实现接口ApplicationContextAwareui
说明:实现该接口的setApplicationContext(ApplicationContext context)方法,并保存ApplicationContext 对象。Spring初始化时,会经过该方法将ApplicationContext对象注入。code
package com.liu.util;xml
import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware;对象
public class SpringContextUtil implements ApplicationContextAware { private static ApplicationContext applicationContext;
/** * 实现ApplicationContextAware接口的context注入函数, 将其存入静态变量. */ public void setApplicationContext(ApplicationContext applicationContext) { SpringContextUtil.applicationContext = applicationContext; // NOSONAR } /** * 取得存储在静态变量中的ApplicationContext. */ public static ApplicationContext getApplicationContext() { checkApplicationContext(); return applicationContext; } /** * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型. */ @SuppressWarnings("unchecked") public static <T> T getBean(String name) { checkApplicationContext(); return (T) applicationContext.getBean(name); } /** * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型. */ @SuppressWarnings("unchecked") public static <T> T getBean(Class<T> clazz) { checkApplicationContext(); return (T) applicationContext.getBeansOfType(clazz); } /** * 清除applicationContext静态变量. */ public static void cleanApplicationContext() { applicationContext = null; } private static void checkApplicationContext() { if (applicationContext == null) { throw new IllegalStateException("applicaitonContext未注入,请在applicationContext.xml中定义SpringContextHolder"); } }
}
四、经过Spring提供的ContextLoader
WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();
wac.getBean(beanID); 说明:注意一点,在服务器启动时,Spring容器初始化时,不能经过以上方法获取Spring 容器。
五、继承自抽象类ApplicationObjectSupport
说明:抽象类ApplicationObjectSupport提供getApplicationContext()方法,能够方便的获取ApplicationContext。 Spring初始化时,会经过该抽象类的setApplicationContext(ApplicationContext context)方法将ApplicationContext 对象注入。
六、继承自抽象类WebApplicationObjectSupport
说明:相似上面方法,调用getWebApplicationContext()获取WebApplicationContext