您的位置:首页 > 移动开发

Spring Bean获取applicationcontext方法

2015-09-17 13:28 411 查看
在Spring Bean中获取上下文对象总结有如下方法:

1、Bean实现ApplicationContextAware接口

在容器启动的时候,会扫描所有实现ApplicationContextAware接口的Bean,并执行里面的setApplicationContext()方法。当然这个Bean首先要交给Spring管理(Bean的scope需要为单例)。在Spring MVC环境中,环境会初始化两个WebXmlApplicationContext容器(父子容器),因此如果此时你的配置扫描到该Bean两次的话,就会造成保存的applicationContext为后来初始化的context(DispatcherServlet启动的context)。因此如需获取父容器(监听器所启动的context),代码如下:

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Controller;

/**
* 获取Spring context对象
*
*/
@Controller("sonHelper")
public class ApplicationHelper implements ApplicationContextAware {

private static ApplicationContext applicationContext;

public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if(null == applicationContext.getParent()) {//父容器的parent为null
this.applicationContext = applicationContext;
}
}

public static ApplicationContext getApplicationContext() {
return ApplicationHelper.applicationContext;
}
}


如果要获取子容器的context的话,getParent() != null即可。

2、使用WebApplicationContextUtils工具类获取

WebApplicationContextUtils.getRequiredWebApplicationContext(request.getSession().getServletContext());
WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext(), WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);


3、继承ApplicationObjectSupport
继承ApplicationObjectSupport类之后,就可以调用里面的getApplicationContext()方法,获取context对象。该类也是实现ApplicationContextAware接口,然后将context设置其中。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息