在Servlet(或者Filter,或者Listener)中使用spring的IOC容器
来源:互联网 发布:沧澜网络代练可信吗 编辑:程序博客网 时间:2024/06/07 13:50
web.xml中的加载顺序为:listener >> filter >> servlet >> spring。其中filter的执行顺序是filter- mapping在web.xml中出现的先后顺序。
加载顺序会影响对spring bean的调用。比如filter 需要用到bean ,但是加载顺序是先加载filter 后加载spring,则filter中初始化操作中的bean为null。所以,如果过滤器中要使用到 bean,可以将spring 的加载改成Listener的方式。
1 <context-param>2 <param-name>contextConfigLocation</param-name>3 <param-value>classpath:applicationContext.xml</param-value>4 </context-param>5 <listener> 6 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 7 </listener>
ContextLoaderListener的作用就是启动Web容器时,自动装配ApplicationContext的配置信息。
如果在web.xml中不写任何参数配置信息,默认的路径是"/WEB-INF/applicationContext.xml",在WEB-INF目录下创建的xml文件的名称必须是applicationContext.xml。如果是要自定义文件名可以在web.xml里加入contextConfigLocation这个context参数。
1 private static ApplicationContext ctx = null;2 public Object getBean(String name) {3 if (ctx == null) {4 ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(this.servletContext);5 }6 return ctx.getBean(name);7 }
在servlet或者filter或者Listener中使用spring的IOC容器的方法是:
WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(request.getSession().getServletContext());
由于spring是注入的对象放在ServletContext中的,所以可以直接在ServletContext取出WebApplicationContext 对象:
WebApplicationContext webApplicationContext = (WebApplicationContext) servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
事实上WebApplicationContextUtils.getWebApplicationContext方法就是使用上面的代码实现的,建议使用上面上面的静态方法
注意:在使用webApplicationContext.getBean("ServiceName")的时候,前面强制转化要使用接口,如果使用实现类会报类型转换错误。如:
LUserService userService = (LUserService) webApplicationContext.getBean("userService");
转载自:http://www.cnblogs.com/warden/p/3508292.html
- 在Servlet(或者Filter,或者Listener)中使用spring的IOC容器
- 在Servlet(或者Filter,或者Listener)中使用spring的IOC容器
- 在Servlet(或者Filter,或者Listener)中使用spring的IOC容器
- 在Servlet(或者Filter,或者Listener)中使用spring的IOC容器
- (转)在Servlet(或者Filter,或者Listener)中使用spring的IOC容器
- 在Servlet(或者Filter,或者Listener)中使用spring的IOC容器
- 在servlet(或者filter或者listener)中使用spring的IOC容器
- 在servlet中或者在filter中获取spring容器中的bean
- 在Servlet Filter中使用Spring容器
- 在Servlet Filter中使用Spring容器
- 如何让servelt和Filter注入到spring容器或者在servlet中调用spring中的bean
- 在SpringBoot中使用 Servlet Filter Listener
- servlet容器中servlet,filter,listener的生命周期
- 在自定义Listener中使用Spring容器管理的bean
- listener或者filter注入service
- spring如何把service注入listener或者filter?
- Filter中访问spring ioc容器中的对象的方式
- 在filter注入或者是得到spring托管的bean
- TNSNAMES.ORA 配置
- struts2与cookie实现自动登录
- weka J48决策树学习
- [***]在Unity 脚本中的作用 C#
- Spring学习笔记(转+改)
- 在Servlet(或者Filter,或者Listener)中使用spring的IOC容器
- python时间戳于时间格式字符串相互转换的方法
- 欢迎使用CSDN-markdown编辑器
- iOS下使用rsa算法与php进行加解密通讯
- 存在hinnt属性的控件。重新hinnt的值(图片+文字)
- C# static
- Android手机平板两不误,使用Fragment实现兼容手机和平板的程序
- IOS 使用XIB 自定义View
- vs2010解决提示“一个或多个多重定义的符号“这种错误