SpringBoot定义事件和监听器

  • 继承事件 ApplicationEvent

  • 定义监听 ApplicationListener

    继承事件 ApplicationEvent

    public class EmailEvent extends ApplicationEvent {
      /**
       * <p>Description:</p>
       */
      private static final long serialVersionUID = 1L;
      public String address;
      public String text;
    
      public EmailEvent(Object source) {
          super(source);
      }
    
      public EmailEvent(Object source, String address, String text) {
          super(source);
          this.address = address;
          this.text = text;
      }
    
      public void print(){
          System.out.println("hello spring event!");
      }
    

}


### 定义监听 ApplicationListener
```java
@Component
public class EmailListener implements ApplicationListener{

    public void onApplicationEvent(ApplicationEvent event) {
        if(event instanceof EmailEvent){
            EmailEvent emailEvent = (EmailEvent)event;
            emailEvent.print();
            System.out.println("the source is:"+emailEvent.getSource());
            System.out.println("the address is:"+emailEvent.address);
            System.out.println("the email's context is:"+emailEvent.text);
        }

    }

}

代码测试

  public static void main(String[] args) {
        ConfigurableApplicationContext applicationContext = SpringApplication.run(Application.class, args);
        EmailEvent emailEvent=new EmailEvent("hello","lxchinesszz@163.com","this is a email text");
        applicationContext.publishEvent(emailEvent);
    }

文章作者: Ciwei
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Ciwei !
 上一篇
Docker安装Sentry日志框架 Docker安装Sentry日志框架
Sentry 是一款基于 Django实现的错误日志收集和聚合的平台,它是 Python 实现的,但是其日志监控功能却不局限于python,对诸如 Node.js, php,ruby, C#,java 等语言的项目都可以做到无缝集成,甚至可
2018-07-25
下一篇 
Spring-Data-Redis 缓存@Cacheable、@CacheEvict、@CachePut的用法 Spring-Data-Redis 缓存@Cacheable、@CacheEvict、@CachePut的用法
Spring为我们提供了几个注解来支持Spring Cache。 @Cacheable 每次查询,将查询结果放入缓存中 相同id,第二次查询时只从缓存中取数据,不从数据库中取,提高数据查询效率 @CacheEvict CacheEvic
2018-07-22
  目录