在普通web项目的servlet和filter中获取spring上下文

本文介绍了如何在Web项目中配置Spring并获取Bean实例。通过在web.xml中配置ContextLoaderListener,可以在Servlet或Filter中轻松地获取ApplicationContext,进而访问Spring管理的Bean。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

之前一直是在web项目中使用struts2然后通过plugin集成spring,action生成的细节全部由plugin实现了,对于我们是透明的。过几天学校留个作业只能用普通的jsp+servlet做,之前一直是透明的使用spring,对spring的初始化及bean的获取一直没什么概念。这回正好用的上,就研究了一下ContextLoaderListener ContextLoader和StrutsSpringObjectFactory的源码。经过一番阅读对spring的初始化和获取bean有了一些印象。



在spring中的org.springframework.beans.factory.BeanFactory接口getBean(String id)用来获取spring管理的bean。而我们一般使用实现了该接口的ApplicationContext接口。所以只要我们在servlet中取得了ApplicationContext接口的实现类,就可以获取spring管理的bean了。



首先是在web.xml中配置listener




Xml代码
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>

<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>



servlet中就可以通过如下方法实现获取spring上下文



Java代码
import javax.servlet.http.HttpServlet;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class NewServlet extends HttpServlet {

public ApplicationContext getApplicationContext(){
return WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
}
}

import javax.servlet.http.HttpServlet;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

public class NewServlet extends HttpServlet {

public ApplicationContext getApplicationContext(){
return WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
}
}



在filter里面server会给它注入一个FilterConfig对象,在filter里可以使用FilterConfig的filterConfig.getServletContext()方法获取servlet上下文,所以在filter里获取spring的上下文方法如下



Java代码
public class CookieFilter implements Filter {

private FilterConfig filterConfig =null;

public ApplicationContext getApplicationContext() {
return WebApplicationContextUtils.getWebApplicationContext(filterConfig.getServletContext());
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值