获取Spring上下文(ApplicationContext)的三种方法

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 public class SpringContextUtil implements ApplicationContextAware {
 2     private static ApplicationContext applicationContext;
 3 
 4     /**
 5      * 实现ApplicationContextAware接口的setApplicationContext注入函数, 将其存入静态变量.
 6      */
 7     public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
 8         SpringContextUtil.applicationContext = applicationContext;
 9     }
10     /**
11      * 取得存储在静态变量中的ApplicationContext.
12      */
13     public static ApplicationContext getApplicationContext() {
14         checkApplicationContext();
15         return applicationContext;
16     }
17 
18     /**
19      * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
20      */
21     @SuppressWarnings("unchecked")
22     public static <T> T getBean(String beanName){
23         checkApplicationContext();
24         return (T) applicationContext.getBean(beanName);
25     }
26     /**
27      * 清除applicationContext静态变量.
28      */
29     public static void cleanApplicationContext(){
30         applicationContext = null;
31     }
32     private static void checkApplicationContext(){
33         if (applicationContext == null){
34             throw new IllegalStateException("applicationContext未注入,请在daos.xml中定义SpringContextUtil");
35         }
36     }
37 
38 }

总结:方式1要依赖Servlet容器,方式2实际只适合测试使用,方式1,2都有明显弊端。建议使用方式3。

原文地址:https://www.cnblogs.com/skyblue123/p/13194654.html