spring中获取applicationContext(2)
2024-10-18 18:26:19
前几天写web项目的时候,用到了spring mvc。
但是又写bean。我要在代码里面生成,而这个bean里面,又有一些属性是通过spring注入的。
所以,只能通过ApplicationContext来获取。
在servlet里面获取ApplicationContext其实可以通过spring提供的方法:
1
|
WebApplicationContextUtils.getWebApplicationContext(ServletContext) |
来获取。
这个方法前提是要在web.xml里面即一个listener:
1
2
3
4
5
6
7
8
9
10
|
< context-param > < param-name >contextConfigLocation</ param-name > < param-value > classpath:spring-servlet.xml, classpath:applicationContext.xml </ param-value > </ context-param > < listener > < listener-class >org.springframework.web.context.ContextLoaderListener</ listener-class > </ listener > |
不过这样子只能在servlet里面获取。
如果要在servlet外获取ApplicationContext呢?
其实可以封装一下的:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
|
package me.idashu.code.util; import org.springframework.context.ApplicationContext; import org.springframework.web.context.WebApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; /** * 描述:ApplicationContext容器 * * @author: dashu * @since: 13-5-11 */ public class AppContext implements ServletContextListener { private static WebApplicationContext springContext; public AppContext() { super (); } public void contextInitialized(ServletContextEvent event) { springContext = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext()); } public void contextDestroyed(ServletContextEvent event) { } public static ApplicationContext getApplicationContext() { return springContext; } } |
还需要在web.xml里面再加条记录:
1
2
3
|
<listener> <listener- class >me.idashu.code.util.AppContext</listener- class > </listener> |
其实就是在content初始化的时候,把ApplicationContext保存起来,下次方便调用。
最新文章
- (实例篇)php 使用redis锁限制并发访问类示例
- Three.js基础部分学习
- formValidator 表单验证
- centos yum 安装 mongodb 以及php扩展
- SAD算法在opencv上的实现代码(c++)
- iOS类实现里面怎么用属性
- HTML5 Canvas arc()函数
- CentOS6.0/RedHat Server 6.4安装配置过程 详细图解!
- cocos2d-x jsb + cocosbuider 适配iphone5 尺寸
- scp和pscp
- 安装升级System.Web.Optimization.dll
- SQL Server 行转列,列转行。多行转成一列
- springmvc返回json字符串中文乱码问题
- Intellij-工程目录下隐藏不想显示的文件和文件夹
- C#+EntityFramework编程方式详细之Database First
- mysql 字符串 拼接 截取 替换
- 简单的MVC与SQL Server Express LocalDB
- @Transactionl注解
- ArrayMap代替HashMap
- sql 内连接、外连接、自然连接等各种连接
热门文章
- springMVC 开涛 Controller接口控制器
- 团队作业第四周(HCL盐酸队)——项目冲刺(第一篇)
- 如何实现让你的网站支持Google Roboto Font
- CxGrid导出Excel时清除颜色的设置
- 开源项目之ASP.NET Core + Vue.js 的前后端分离的通用后台管理系统框架
- .net core Memcached使用
- 区别script中的type=”text/javascript”和language=”Javascript”
- Unity里vertexShader里压扁模型来实现比较low的阴影
- 对表单控制是否提交 需要在方法名前面加上 return
- Mysql分析-profile详解