Spring 事件(2)- 自定义事件

除了内置事件,Spring中也可以使用自定义事件。

怎样使用自定义事件:

  • 创建事件类 – 扩展ApplicationEvent类,创建事件类。
  • 创建发送类 – 发送类获取ApplicationEventPublisher实例发送事件。
  • 创建监听类 – 实现ApplicationListener接口,创建监听类。

事件类

事件类用于存储事件数据。下面创建一个简单的事件类。

CustomEvent.java

import org.springframework.context.ApplicationEvent;

public class CustomEvent extends ApplicationEvent {

    public CustomEvent(Object source, String message) {
        super(source);
    }

    public String toString() {
        return "我是自定义事件";
    }
}

发送类

发送类创建事件对象并发送。

要发送事件,这里介绍2种方法:

  1. 使用@autowired注解注入ApplicationEventPublisher实例。

CustomEventPublisher.java

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;

public class CustomEventPublisher {

  @Autowired
  private ApplicationEventPublisher publisher;

  public void publish() {
    CustomEvent event = new CustomEvent(this);
    publisher.publishEvent(event);
  }
}
  1. 发送类实现ApplicationEventPublisherAware接口,获取ApplicationEventPublisher实例。

CustomEventPublisher.java

import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;

public class CustomEventPublisher implements ApplicationEventPublisherAware {

  private ApplicationEventPublisher publisher;

  // 必须重写这个方法获取ApplicationEventPublisher
  public void setApplicationEventPublisher (ApplicationEventPublisher publisher){
    this.publisher = publisher;
  }

  public void publish() {
    CustomEvent event = new CustomEvent(this);
    publisher.publishEvent(event);
  }
}

如果发送类实现了ApplicationEventPublisherAware接口,发送类必须声明为bean,Spring容器将其标识为事件发送者。

<bean id="customEventPublisher" class="CustomEventPublisher"/>

监听类

监听类监听事件。监听类必须实现ApplicationListener接口,并且被定义为Bean以便Spring容器可以加载它。

beans.xml

<bean id="customEventHandler" class="CustomEventHandler"/>

CustomEventHandler.java

import org.springframework.context.ApplicationListener;

public class CustomEventHandler implements ApplicationListener<CustomEvent> { 
  public void onApplicationEvent(CustomEvent event) {
    System.out.println("收到事件:" + event.toString());
  }
}

运行

测试自定义事件。

Test.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
  public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml");

    CustomEventPublisher publisher = (CustomEventPublisher) context.getBean("customEventPublisher");
    publisher.publish();
  }
}


浙ICP备17015664号 浙公网安备 33011002012336号 联系我们 网站地图  
@2019 qikegu.com 版权所有,禁止转载