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} 来使用。

转载于:https://www.cnblogs.com/demingblog/p/3849119.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值