1.通过WebApplicationUtils工具类获取,使用该方法的必须依赖Servlet容器。 方法如下:
ApplicationContext ap = WebApplicationUtils.getWebApplicationContext(servletContextParam)
其中servletContextParam是你需要传入的Servlet容器参数。
2. 通过ClassPathXmlApplicationContext类获取。
ApplicationContext ap = new ClassPathXmlApplicationContext("applicationContext.xml");
3.创建一个自己的工具类(SpringContextUtil)实现Spring的ApplicationContextAware接口。最后在Spring配置文件中注册你的工具类。配置如下:
<bean id="springContextUtil" class="com.fubo.utils.spring.SpringContextUtil" lazy-init="false"/>
SpringContextUtil实现代码如下:
1 package com.fubo.utils.spring; 2 import javax.servlet.http.HttpServletRequest; 3 import javax.servlet.http.HttpServletResponse; 4 5 import org.springframework.context.ApplicationContext; 6 import org.springframework.context.ApplicationContextAware; 7 import org.springframework.context.support.ClassPathXmlApplicationContext; 8 import org.springframework.web.context.support.WebApplicationContextUtils; 9 /** 10 * 实现对spring context 的管理 11 * @author FB 12 * @2017年3月29日 13 * @上午9:07:27 14 * @ 15 */ 16 public class SpringContextUtils implements ApplicationContextAware { 17 18 private static ApplicationContext applicationContext; 19 20 /** 21 * 实现ApplicationContextAware接口的context注入函数, 将其存入静态变量. 22 */ 23 public void setApplicationContext(ApplicationContext applicationContext) { 24 SpringContextUtil.applicationContext = applicationContext; // NOSONAR 25 } 26 27 /** 28 * 取得存储在静态变量中的ApplicationContext. 29 */ 30 public static ApplicationContext getApplicationContext() { 31 checkApplicationContext(); 32 return applicationContext; 33 } 34 35 /** 36 * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型. 37 */ 38 @SuppressWarnings("unchecked") 39 public static <T> T getBean(String name) { 40 checkApplicationContext(); 41 return (T) applicationContext.getBean(name); 42 } 43 44 /** 45 * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型. 46 */ 47 @SuppressWarnings("unchecked") 48 public static <T> T getBean(Class<T> clazz) { 49 checkApplicationContext(); 50 return (T) applicationContext.getBeansOfType(clazz); 51 } 52 53 /** 54 * 清除applicationContext静态变量. 55 */ 56 public static void cleanApplicationContext() { 57 applicationContext = null; 58 } 59 60 private static void checkApplicationContext() { 61 if (applicationContext == null) { 62 throw new IllegalStateException( 63 "applicaitonContext未注入,请在applicationContext.xml中定义SpringContextUtil"); 64 } 65 } 66 67 68 public static void setHttpRequestResponseUtil(HttpServletRequest request, HttpServletResponse response){ 69 responseThreadLocal.set(response); 70 ApplicationContext ap = WebApplicationContextUtils.getWebApplicationContext(null); 71 } 72 public static HttpServletResponse getHttpResponse(){ 73 return responseThreadLocal.get(); 74 } 75 76 public static void clean(){ 77 responseThreadLocal.remove(); 78 } 79 80 private static final ThreadLocal<HttpServletResponse> responseThreadLocal = new ThreadLocal(); 81 82 }
总结:方式1要依赖Servlet容器,方式2实际只适合测试使用,方式1,2都有明显弊端。建议使用方式3。