spring事件的使用分享

102 阅读1分钟

1、spring的普通事件

import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

/**
 * 普通事件
 *
 * @author : erik.zhou
 * @date : 2023/01/30/14:25
 * @description :
 */
@Component
public class ContextRefreshedEventListener implements ApplicationListener<ContextRefreshedEvent> {

   @Override
   public void onApplicationEvent(ContextRefreshedEvent event) {
      System.out.println("刷新/打开事件:" + this.getClass().getName());
   }
}
  • 此事件会在应用开始的时候就触发,或者自己调用的时候触发

2、普通事件

@Bean
public ApplicationListener applicationListener() {
   return new ApplicationListener() {
      @Override
      public void onApplicationEvent(ApplicationEvent event) {
         System.out.println("接收到了一个事件1" + event);
      }
   };
}
  • 此事件会在应用开始的时候就触发,或者自己调用的时候触发

3、自定义事件

import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

/**
 * 自定义事件
 *
 * @author : erik.zhou
 * @date : 2023/01/30/14:21
 * @description :
 */
@Component
public class MailSenderListener implements ApplicationListener<MailSendEvent> {
   @Override
   public void onApplicationEvent(MailSendEvent event) {
      System.out.println("邮件发送器的 resource:" + event.getSource() + "邮件发送器的 msg:" + event.getMsg());
   }
}
import org.springframework.context.ApplicationContext;
import org.springframework.context.event.ApplicationContextEvent;

/**
 * 自定义事件
 *
 * @author : erik.zhou
 * @date : 2023/01/30/14:22
 * @description :
 */
public class MailSendEvent extends ApplicationContextEvent {
   private String msg;

   public MailSendEvent(ApplicationContext source, String msg) {
      super(source);
      this.msg = msg;
   }

   public String getMsg() {
      return msg;
   }

   public void setMsg(String msg) {
      this.msg = msg;
   }
}

事件的使用:

@Component
public class UserService implements ApplicationContextAware {

   @Autowired
   private OrderService orderService;

   private ApplicationContext applicationContext;

   public void test() {
      System.out.println(orderService);
      applicationContext.publishEvent("erik");
      applicationContext.publishEvent(new MailSendEvent(applicationContext, "wwww"));
   }


   @Override
   public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
      this.applicationContext = applicationContext;
   }
}

4、事件关闭

/**
 * 关闭事件
 *
 * @author : erik.zhou
 * @date : 2023/01/30/14:25
 * @description :
 */
@Component
public class ContextClosedEventListener implements ApplicationListener<ContextClosedEvent> {
   @Override
   public void onApplicationEvent(ContextClosedEvent event) {
      System.out.println("关闭事件:" + this.getClass().getName());
   }
}