springBoot的事件机制GenericApplicationListener用法解析
什么是ApplicationContext?
它是Spring的核心,Context我们通常解释为上下文环境,但是理解成容器会更好些。 ApplicationContext则是应用的容器。
Spring把Bean(object)放在容器中,需要用就通过get方法取出来。
ApplicationEvent
- 是个抽象类,里面只有一个构造函数和一个长整型的timestamp。
- springboot的event的类型:
- ApplicationStartingEvent
- ApplicationEnvironmentPreparedEvent
- ApplicationContextInitializedEvent
- ApplicationPreparedEvent
- ContextRefreshedEvent
- ServletWebServerInitializedEvent
- ApplicationStartedEvent
- ApplicationReadyEvent
ApplicationListener
是一个接口,里面只有一个onApplicationEvent方法。所以自己的类在实现该接口的时候,要实现该方法。
ApplicationListener的封装类
- GenericApplicationListener
- GenericApplicationListenerAdapter
- SmartApplicationListener
关系
如果在上下文中部署一个实现了ApplicationListener接口的bean,那么每当在一个ApplicationEvent发布到 ApplicationContext时,这个bean得到通知。其实这就是标准的Oberver设计模式。
注意
要配置META-INF/spring.factories文件,并在文件中实现
使用
// 第一种方式
public class AiInfluxdbApplicationListener implements GenericApplicationListener {
@Override
public int getOrder() {
return Ordered.LOWEST_PRECEDENCE;
}
@Override
public boolean supportsEventType(ResolvableType eventType) {
return ApplicationReadyEvent.class.isAssignableFrom(eventType.getRawClass());
}
@Override
public void onApplicationEvent(ApplicationEvent event) {
System.out.print("here is ApplicationReadyEvent");
}
}
//第二种方式
public class ConfigApplicationListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent>, Ordered {
@Override
public int getOrder() {
return HIGHEST_PRECEDENCE;
}
@Override
public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
}
}
//META-INF/spring.factories文件定义
org.springframework.context.ApplicationListener=\
com.demotest.core.ApplicationStartListener
栏 目:JAVA代码
下一篇:spring security在分布式项目下的配置方法(案例详解)
本文标题:springBoot的事件机制GenericApplicationListener用法解析
本文地址:http://www.codeinn.net/misctech/108334.html


阅读排行
- 1Java Swing组件BoxLayout布局用法示例
- 2java中-jar 与nohup的对比
- 3Java邮件发送程序(可以同时发给多个地址、可以带附件)
- 4Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type异常
- 5Java中自定义异常详解及实例代码
- 6深入理解Java中的克隆
- 7java读取excel文件的两种方法
- 8解析SpringSecurity+JWT认证流程实现
- 9spring boot里增加表单验证hibernate-validator并在freemarker模板里显示错误信息(推荐)
- 10深入解析java虚拟机




