SpringBoot 监听器ApplicationListener的使用

SpringBoot2.0 监听器ApplicationListener的使用

文章目录

  • SpringBoot2.0 监听器ApplicationListener的使用
  • 前言
  • 支持的事件类型
  • 监听器的使用
    • 自定义监听器类bean
    • addListeners方式

前言

当我们使用spring boot项目开发时候,碰到应用启动后做一些初始化操作,可以使用ApplicationListener。比如:netty 随着应用启动完成后进行初始化、初始化定时任务

支持的事件类型

  1. ApplicationFailedEvent:该事件为spring boot启动失败时的操作

  2. ApplicationPreparedEvent:上下文context准备时触发

  3. ApplicationReadyEvent:上下文已经准备完毕的时候触发

  4. ApplicationStartedEvent:spring boot 启动监听类

  5. SpringApplicationEvent:获取SpringApplication

  6. ApplicationEnvironmentPreparedEvent:环境事先准备

监听器的使用

自定义监听器类bean

首先定义一个自己使用的监听器类并实现ApplicationListener接口。

@Componen  
public class MessageReceiver implements ApplicationListener<ApplicationReadyEvent> { private Logger logger = LoggerFactory.getLogger(MessageReceiver.class); private UserService userService = null;
    @Override public void onApplicationEvent(ApplicationReadyEvent event) {
        ConfigurableApplicationContext applicationContext = event.getApplicationContext();//解决userService一直为空
     userService = applicationContext.getBean(UserService.class);   
     System.out.println("name"+userService.getName());
    }
}

addListeners方式

通过SpringApplication类中的addListeners方法将自定义的监听器注册进去

public class Application { public static void main(String\[\] args) {
        SpringApplication application = new SpringApplication(Application.class);
        application.addListeners(new MessageReceiver());
        application.run(args);
    
    }
}

你可能感兴趣的:(spring-boot,Spring,Boot实战学习)