Spring上下文(ApplicationContext)的获取有三种方式。
1.通过WebApplicationUtils工具类获取。WebApplicationUtils类是在Spring框架基础包spring-web-3.2.0. RELEASE.jar(我使用的是3.2.0版的jar包,大家可以去spring官网下载最新版的jar)中的类。使用该方法的必须依赖Servlet容器。 使用方法如下:
ApplicationContext ap =WebApplicationUtils.getWebApplicationContext(servletContextParam)
其中servletContextParam是你需要传入的Servlet容器参数。
2. 通过ClassPathXmlApplicationContext类获取。ClassPathXmlApplicationContext 类是在Spring框架基础包spring-context-3.2.0. RELEASE.jar(我使用的是3.2.0版的jar包,大家可以去spring官网下载最新版的jar)中的类。使用方法如下:
ApplicationContext ap = new ClassPathXmlApplicationContext("applicationContext.xml");
其中applicationContext.xml文件放在src下面,这样就保证可以读取到该文件。这个XML的作用是集中配置和管理所有Bean。
applicationContext.xml代码:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
//中间部分是你自己配置的所有bean
</beans>
3.创建一个自己的工具类(SpringContextHolder)实现Spring的ApplicationContextAware接口。实现代码如下:
@Component
public class SpringContextHolder implements ApplicationContextAware {
private static ApplicationContext context;
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return context;
}
}
总结:方式1要依赖Servlet容器,方式2实际只适合测试使用,方式1,2都有明显弊端。建议使用方式3。