Spring的web应用启动加载数据字典方法
在一个基于Spring的web项目中,当我们需要在应用启动时加载数据字典时,可写一个监听实现javax.servlet.ServletContextListener
实现其中的contextInitialized(ServletContextEvent sce) 方法完成,初始化的操作。代码示例如下
一、监听程序
import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import org.springframework.context.ApplicationContext; import org.springframework.web.context.support.WebApplicationContextUtils; public class InitDicListener implements ServletContextListener { public void contextInitialized(ServletContextEvent sce) { //spring 上下文 ApplicationContext appContext = WebApplicationContextUtils.getWebApplicationContext(sce.getServletContext()); /* ServiceBean bean1=appContext.getBean("xxx"); ...业务方法,加载数据字典等。 */ } public void contextDestroyed(ServletContextEvent sce) { } }
二、配置文件中加入配置
在web.xml中加入 监听配置, 但要写在Spring配置的下面,这样我们自定义的监听会在Spring监听之后启动,这个时候在我们自定义的监听程序中能够得到Spring的上下文。
因为,当web.xml中有多个<listener>配置时,排在前面的先启动
<!-- Spring 框架 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 加载数据字典 在Spring配置的下面--> <listener> <listener-class>msdemo.listener.InitDicListener</listener-class> </listener>
三、数据字典使用
程序中 通过 ServletContext的getAttribute(name) 方法来获得 字典数据
jsp页面中 ${name} 来使用。
如果我的文章对你有帮助,欢迎微信支付打赏。

分类:
学习积累
, Spring/Springboot
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构