spring容器初始化之后执行某些系统初始化动作

最近自己所在的项目中出现此种情形:项目启动后,需要做一些初始化动作,如,读取配置文件、查询数据库数据存入缓存等。参考前人写的代码的实现方式如下:

思路:编写一个系统初始化类,该类实现ServletContextListenner接口,并实现contextInitialized(),和contextDestory()方法。

public class SystemInitAfterSpringInited implements ServletContextListenner{

    @Override //容器初始化后执行

    public void contextInitialized(ServlectContextEvent event){

    //通过event 获取上下文实例

    WebApplicationContext application = WebApplicationContextUtils.getWebApplicationContext(event.getServlectContext);

    //通过应用上下文实例,获取由spring容器管理的bean

    SomeBean bean1 = (SomeBean) application.getBean("beanName1");

    bean1.doSomething();

    }

    @Override //容器销毁之前执行

    public void contextDestory(ServlectContextEvent event){

    //通过event 获取上下文实例

    WebApplicationContext application = WebApplicationContextUtils.getWebApplicationContext(event.getServlectContext);

    //通过应用上下文实例,获取由spring容器管理的bean

    SomeBean bean2 = (SomeBean) application.getBean("beanName2");

    bean2.doSomething();

    }

}

你可能感兴趣的:(spring容器初始化之后执行某些系统初始化动作)