Spring中ApplicationContextAware实现获取bean的工具类,在servlet中通过servletContext获取application

1、提供一个util类获取spring容器中的对象。GetBeanUtil,该类实现ApplicationContextAware

package utils;

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

//使用该方法的时候注意加载器是否是同一个
public class GetBeanUtil implements ApplicationContextAware{

	public static ApplicationContext context;
	//实现方法,在bean容器初始化的时候会自动注入 Application对象
	public void setApplicationContext(ApplicationContext paramApplicationContext)
			throws BeansException {
		context = paramApplicationContext;
	}

	//提供静态的方法获取bean对象
	public static <T> T getBean(String id,Class clazz){
		System.out.println(context+">>>>>>>>>>>>>>>>>>>>>>>>>>>");
		T bean = (T) context.getBean(id, clazz);
		return bean;
	}
	
}



2、在beans.xml中注册GetBeanUtil类(使用注解),spring容器初始化的时候回将Application对象注入到GetBeanUtil工具类中

<bean id = "util" class = "utils.GetBeanUtil"/>


3、直接调用GetBeanUtil.getBean("user",User.class) 获取spring容器中的user对象


二、通过servletContext获取application对象

当 Web 应用集成 Spring 容器后,代表 Spring 容器的WebApplicationContext对象将以

WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE 为键存放在ServletContext的属性列表中。您当然可以直接通过以下语句获取 WebApplicationContext:

WebApplicationContext wac = (WebApplicationContext)servletContext.

getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);


但通过位于 org.springframework.web.context.support 包中的WebApplicationContextUtils 工具类获取 WebApplicationContext 更方便:

WebApplicationContext wac =WebApplicationContextUtils.

getWebApplicationContext(servletContext);

当 ServletContext 属性列表中不存在 WebApplicationContext 时,getWebApplicationContext() 方法不会抛出异常,它简单地返回 null。如果后续代码直接访问返回的结果将引发一个 NullPointerException 异常,而 WebApplicationContextUtils 另一个 getRequiredWebApplicationContext(ServletContext sc) 方法要求 ServletContext 属性列表中一定要包含一个有效的 WebApplicationContext 对象,否则马上抛出一个 IllegalStateException 异常。我们推荐使用后者,因为它能提前发现错误的时间,强制开发者搭建好必备的基础设施。


public class DemoServlet extends HttpServlet {

	public void init() throws ServletException {
		super.init();
		ServletContext servletContext = this.getServletContext();
		WebApplicationContext ctx = WebApplicationContextUtils
				.getWebApplicationContext(servletContext);
		demoWS = (ISignpicWS) ctx.getBean("demoWS");
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
	}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值