在Spring+Struts+Hibernate中,有时需要使用到Spring上下文。项目启动时,会自动根据applicationContext配置文件初始化上下文,可以使用ApplicationContextAware接口去获得Spring上下文。创建以下的类:
package com.linuxidc.tool;
import org.springframework.beans.BeansException;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;import org.springframework.stereotype.Component;
@Componentpublic class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { SpringContextUtil.applicationContext = applicationContext; }
public static ApplicationContext getApplicationContext() { return applicationContext; }
@SuppressWarnings("unchecked") public static <T> T getBean(String name) throws BeansException { return (T) applicationContext.getBean(name); }
}
在applicationContext配置文件中配置这个类:
<bean id="springContextUtil" class="com.linuxidc.tool.SpringContextUtil" />
这样,在根据applicationContext初始化上下文时,会自动调用setApplicationContext()方法去获取ApplicationContext。
也可以使用
ClassPathXmlApplicationContext("applicationContext.xml")
去获取ApplicationContext,不过这相当于把重新初始化一次上下文,速度会很慢,而且逼格也不高,不推荐使用。
本文永久更新链接地址:http://www.xuebuyuan.com/Linux/2017-01/139353.htm
以上就上有关Spring获取ApplicationContext的相关介绍,要了解更多ApplicationContext,Spring获取,Spring获取ApplicationContext,编程,Linux编程,Linux Shell,Android,Android教程,JAVA,C语言,Python,HTML5内容请登录学步园。