Spring Bean获取applicationcontext方法

在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设置其中。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值