Spring Boot 自定义事件

Spring 官方文档翻译如下 :

ApplicationContext 通过 ApplicationEvent 类和 ApplicationListener 接口进行事件处理。 如果将实现 ApplicationListener 接口的 bean 注入到上下文中,则每次使用 ApplicationContext 发布 ApplicationEvent 时,都会通知该 bean。 本质上,这是标准的观察者设计模式。 Spring的事件(Application Event)其实就是一个观察者设计模式,一个 Bean 处理完成任务后希望通知其它 Bean 或者说 一个Bean 想观察监听另一个Bean的行为。

Spring 事件只需要几步:

  1. 自定义事件,继承 ApplicationEvent
  2. 定义监听器,实现 ApplicationListener 或者通过 @EventListener 注解到方法上
  3. 定义发布者,通过 ApplicationEventPublisher

代码示例:

自定义event

/**
 * 自定义事件
 *
 * @author lz
 * @date 2019/8/13
 */
@EqualsAndHashCode(callSuper = true)
@Data
public class DemoEvent extends ApplicationEvent {
    private String message;

    public DemoEvent(Object source, String message) {
        super(source);
        this.message = message;
    }
}

自定义监听器

编程式——>实现ApplicationListener 接口

/**
 * 自定义监听
 *
 * @author lz
 * @date 2019/8/13
 */
@Component
public class DemoListener implements ApplicationListener<DemoEvent> {
    @Override
    public void onApplicationEvent(DemoEvent event) {
        System.out.println("自定义事件");
        System.out.println(event);
    }
}

注解式——> 添加@EventListener注解

/**
 * 自定义监听
 *
 * @author lz
 * @date 2019/8/13
 */
@Component
public class DemoListener2 {

    @EventListener
    public void onApplicationEvent(DemoEvent demoEvent) {
        System.out.println("收到了:" + demoEvent.getSource() + "消息;时间:" + emoEvent.getTimestamp());
    }
}

消息发布者

/**
 * 自定义监听
 *
 * @author lz
 * @date 2019/8/13
 */
@Component
public class DemoPublisher {

    private final ApplicationContext applicationContext;

    @Autowired
    public DemoPublisher(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    public void publish(String message) {
        applicationContext.publishEvent(new DemoEvent(this, message));
    }

}

测试

/**
 * 启动
 *
 * @author lz
 * @date 2019/8/13
 */
@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext run = SpringApplication.run(DemoApplication .class, args);
        run.publishEvent(new DemoEvent(DemoApplication .class, "随便"));
    }

}

结果

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.1.7.RELEASE)

2019-08-13 10:39:19.611  INFO 13600 --- [           main] com.example.demo655.DemoApplication   : Starting DemoApplication on DESKTOP-AQTLR8E with PID 13600 (E:\IdeaProjects6\demo655\target\classes started by ** in E:\IdeaProjects6\demo655)
2019-08-13 10:39:19.613  INFO 13600 --- [           main] com.example.demo655.DemoApplication   : No active profile set, falling back to default profiles: default
2019-08-13 10:39:20.360  INFO 13600 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2019-08-13 10:39:20.374  INFO 13600 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-08-13 10:39:20.375  INFO 13600 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.22]
2019-08-13 10:39:20.450  INFO 13600 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-08-13 10:39:20.450  INFO 13600 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 784 ms
2019-08-13 10:39:20.582  INFO 13600 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-08-13 10:39:20.700  INFO 13600 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2019-08-13 10:39:20.702  INFO 13600 --- [           main] com.example.demo655.DemoApplication   : Started DemoApplication in 1.373 seconds (JVM running for 2.255)
自定义事件
DemoEvent(message=随便)

spring boot 系统启动事件

最后分享一下springboot提供的一些事件

image

系统启动时,执行顺序为:application starting > application prepared > application ready

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

扫码关注云+社区

领取腾讯云代金券