event,listener是观察者模式一种体现。主要作用是接耦,另外强调一点是listener默认是同步的,想异步的话,方法加@Async

自定义Listerner和Event

Example(未测试)

image.png
自定义事件BookingEvent

  1. package per.java.basic.example.listener.applicationEvent;
  2. import org.springframework.context.ApplicationEvent;
  3. public class BookingEvent extends ApplicationEvent {
  4. private String author;
  5. /**
  6. * Create a new {@code ApplicationEvent}.
  7. *
  8. * @param source the object on which the event initially occurred or with
  9. * which the event is associated (never {@code null})
  10. */
  11. public BookingEvent(Object source) {
  12. super(source);
  13. }
  14. public BookingEvent(Object source, String author) {
  15. super(source);
  16. this.author = author;
  17. }
  18. public String getAuthor() {
  19. return "author:" + author;
  20. }
  21. }

发布者BookingEventPublisher

  1. package per.java.basic.example.listener.applicationEvent;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.context.ApplicationContext;
  4. import org.springframework.stereotype.Component;
  5. @Component
  6. public class BookingEventPublisher {
  7. @Autowired
  8. private ApplicationContext applicationContext;
  9. public void publishBookingEvent(BookingEvent event) {
  10. applicationContext.publishEvent(event);
  11. }
  12. }

监听器BookingEventsListener

  1. package per.java.basic.example.listener.applicationEvent;
  2. import org.springframework.context.ApplicationListener;
  3. import org.springframework.stereotype.Component;
  4. @Component
  5. public class BookingEventsListener implements ApplicationListener<BookingEvent> {
  6. // 默认是阻塞同步的,如果想异步加此注解
  7. @Async
  8. @Override
  9. public void onApplicationEvent(BookingEvent event) {
  10. System.out.println("onApplicationEvent : " + event.getAuthor());
  11. }
  12. }

内置Listener

监听器通常用于监听 Web 应用程序中对象的创建、销毁等动作的发送,同时对监听的情况作出相应的处理,最常用于统计网站的在线人数、访问量等。
监听器大概分为以下几种:

  • ServletContextListener:用来监听 ServletContext 属性的操作,比如新增、修改、删除。
  • HttpSessionListener:用来监听 Web 应用种的 Session 对象,通常用于统计在线情况。
  • ServletRequestListener:用来监听 Request 对象的属性操作。

例如统计当前在线人数demo如下:

  1. public class MyHttpSessionListener implements HttpSessionListener {
  2. public static AtomicInteger userCount = new AtomicInteger(0);
  3. @Override
  4. public synchronized void sessionCreated(HttpSessionEvent se) {
  5. userCount.getAndIncrement();
  6. se.getSession().getServletContext().setAttribute("sessionCount", userCount.get());
  7. log.info("【在线人数】人数增加为:{}", userCount.get());
  8. //此处可以在ServletContext域对象中为访问量计数,然后传入过滤器的销毁方法
  9. //在销毁方法中调用数据库入库,因为过滤器生命周期与容器一致
  10. }
  11. @Override
  12. public synchronized void sessionDestroyed(HttpSessionEvent se) {
  13. userCount.getAndDecrement();
  14. se.getSession().getServletContext().setAttribute("sessionCount", userCount.get());
  15. log.info("【在线人数】人数减少为:{}", userCount.get());
  16. }
  17. }