zoukankan      html  css  js  c++  java
  • ApplicationListener用法

    ApplicationListener是spring提供的接口,作用是在web服务器启动时去加载某些程序。

    用法:

    1、实现ApplicationListener接口,并重写onApplicationEvent方法

    @Component
    public class StartLoader implements ApplicationListener<ContextRefreshedEvent> {
    
        @Override
        public void onApplicationEvent(ContextRefreshedEvent event) {
            if(event.getApplicationContext().getParent() == null){
                System.out.println("系统初始化...");
                try {
                    Thread.currentThread().sleep(1000);
                } catch (Exception e) {
                    System.out.println("初始化异常...");
                    e.printStackTrace();
                }
                System.out.println("初始化完成...");
            }
        }
    }
    event.getApplicationContext().getParent() == null:
    ApplicationContext就是Root容器,所以不存在父容器

    2、创建spring的应用上下文(ApplicationContext.xml),并配置注解扫描(或配置bean)

    <!--自动扫描含有@Component将其注入为bean -->  
    <context:component-scan base-package="com.aidilude.component" />

    3、配置web.xml

       <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
                classpath:spring.xml
            </param-value>
        </context-param>
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
    ContextLoaderListener的作用了:
    在web容器初始化的时候,加载spring的应用上下文配置文件(ApplicationContext.xml),与context-param标签一起使用
  • 相关阅读:
    《构建之法》阅读报告
    教务管理系统类图及数据库E/R图
    设计模式:抽象工厂
    结对项目:四则运算程序测试
    Leetcode笔记之57和为s的连续正数序列
    Leetcode笔记之1103分糖果 II
    Leetcode笔记之199二叉树的右视图
    每日Scrum(9)
    每日Scrum(7)
    每日Scrum(6)
  • 原文地址:https://www.cnblogs.com/javafucker/p/8628738.html
Copyright © 2011-2022 走看看