zoukankan      html  css  js  c++  java
  • ApplicationListener接口,在spring容器初始化后执行的方法

    一、如果我们希望在Spring容器将所有的Bean都初始化完成之后,做一些操作,那么就可以使用ApplicationListener接口,实现ApplicationListener接口中的onApplicationEvent方法,此方法会在容器中所有bean初始化完成后执行。

    @Component
    public class MyApplicationListener implements ApplicationListener<ContextRefreshedEvent> {
        @Autowired
        private ApplicationContext applicationContext;
    
        @Override
        public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
            System.out.println("容器初始化完成。。。。。。。。");
            
        }
    }

    二、在web开发中,会存在一个问题,系统会存在两个容器,一个是spring的ioc容器(父),一个是springmvc的ioc容器(子),这两个容器是父子关系。这样就会造成onApplicationEvent方法被执行两次。为了解决此问题,我们可以判断当前容器是否父容器,是父容器才执行下边的代码。步骤如下:通过参数contextRefreshedEvent获取容器对象,在根据容器对象获取其父容器,如果父容器为空,则说明当前容器是父容器。

    @Component
    public class MyApplicationListener implements ApplicationListener<ContextRefreshedEvent> {
        @Autowired
        private ApplicationContext applicationContext;
    
        @Override
        public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
            ApplicationContext parent = contextRefreshedEvent.getApplicationContext().getParent();
            if (parent == null){
                System.out.println("容器初始化完成。。。。。。。。");
            }
    
        }
    }
  • 相关阅读:
    DRF之url注册器组件
    序列化组件的使用及接口设计和优化
    Django 内置字段
    Django 的 ModelForm组件
    Django组件 中间件
    csrf
    django使用redis做缓存
    微信消息推送
    自定制serilazry字段
    小知识,大智慧(restframework 拾忆)
  • 原文地址:https://www.cnblogs.com/bear7/p/13657379.html
Copyright © 2011-2022 走看看