Spring Events – Spring活动

最后修改: 2014年 11月 10日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this tutorial, we’ll be discussing how to use events in Spring.

在本教程中,我们将讨论如何在Spring中使用事件。

Events are one of the more overlooked functionalities in the framework but also one of the more useful. And like many other things in Spring, event publishing is one of the capabilities provided by ApplicationContext.

事件是框架中比较容易被忽视的功能之一,但也是比较有用的功能之一。像Spring中的许多其他东西一样,事件发布是ApplicationContext提供的功能之一。

There are a few simple guidelines to follow:

有几个简单的准则可以遵循。

  • The event class should extend ApplicationEvent if we’re using versions before Spring Framework 4.2. As of the 4.2 version, the event classes no longer need to extend the ApplicationEvent class.
  • The publisher should inject an ApplicationEventPublisher object.
  • The listener should implement the ApplicationListener interface.

2. A Custom Event

2.一个自定义事件

Spring allows us to create and publish custom events that by default are synchronous. This has a few advantages, such as the listener being able to participate in the publisher’s transaction context.

Spring允许我们创建和发布自定义事件,默认情况下是同步的。这有几个优点,比如监听器能够参与发布者的事务上下文。

2.1. A Simple Application Event

2.1.一个简单的应用事件

Let’s create a simple event class — just a placeholder to store the event data.

让我们创建一个简单的事件类–只是一个存储事件数据的占位符。

In this case, the event class holds a String message:

在这种情况下,事件类持有一个字符串消息。

public class CustomSpringEvent extends ApplicationEvent {
    private String message;

    public CustomSpringEvent(Object source, String message) {
        super(source);
        this.message = message;
    }
    public String getMessage() {
        return message;
    }
}

2.2. A Publisher

2.2.一个出版商

Now let’s create a publisher of that event. The publisher constructs the event object and publishes it to anyone who’s listening.

现在让我们创建该事件的发布者。发布者构建事件对象并将其发布给任何正在收听的人。

To publish the event, the publisher can simply inject the ApplicationEventPublisher and use the publishEvent() API:

要发布事件,发布者可以简单地注入ApplicationEventPublisher并使用publishEvent() API。

@Component
public class CustomSpringEventPublisher {
    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    public void publishCustomEvent(final String message) {
        System.out.println("Publishing custom event. ");
        CustomSpringEvent customSpringEvent = new CustomSpringEvent(this, message);
        applicationEventPublisher.publishEvent(customSpringEvent);
    }
}

Alternatively, the publisher class can implement the ApplicationEventPublisherAware interface, and this will also inject the event publisher on the application startup. Usually, it’s simpler to just inject the publisher with @Autowire.

另外,发布者类可以实现ApplicationEventPublisherAware接口,这也会在应用程序启动时注入事件发布者。通常,用@Autowire注入发布者会更简单。

As of Spring Framework 4.2, the ApplicationEventPublisher interface provides a new overload for the publishEvent(Object event) method that accepts any object as the event. Therefore, Spring events no longer need to extend the ApplicationEvent class.

从Spring Framework 4.2开始,ApplicationEventPublisher接口为publishEvent(Object event)方法提供了一个新的重载,该方法接受任何对象作为事件。因此,Spring事件不再需要扩展ApplicationEvent类。

2.3. A Listener

2.3.一个听众

Finally, let’s create the listener.

最后,让我们创建听众。

The only requirement for the listener is to be a bean and implement ApplicationListener interface:

对监听器的唯一要求是成为一个Bean并实现ApplicationListener接口。

@Component
public class CustomSpringEventListener implements ApplicationListener<CustomSpringEvent> {
    @Override
    public void onApplicationEvent(CustomSpringEvent event) {
        System.out.println("Received spring custom event - " + event.getMessage());
    }
}

Notice how our custom listener is parametrized with the generic type of custom event, which makes the onApplicationEvent() method type-safe. This also avoids having to check if the object is an instance of a specific event class and casting it.

请注意我们的自定义监听器是如何以自定义事件的通用类型为参数的,这使得onApplicationEvent()方法是类型安全的。这也避免了检查对象是否是一个特定的事件类的实例并进行铸造。

And, as already discussed (by default Spring events are synchronous), the doStuffAndPublishAnEvent() method blocks until all listeners finish processing the event.

而且,正如已经讨论过的(默认情况下Spring事件是同步的),doStuffAndPublishAnEvent()方法会阻塞,直到所有监听器完成事件的处理。

3. Creating Asynchronous Events

3.创建异步事件

In some cases, publishing events synchronously isn’t really what we’re looking for — we may need async handling of our events.

在某些情况下,同步发布事件并不是我们真正想要的–我们可能需要对事件进行异步处理。

We can turn that on in the configuration by creating an ApplicationEventMulticaster bean with an executor.

我们可以通过创建一个带有执行器的ApplicationEventMulticasterBean来在配置中打开它。

For our purposes here, SimpleAsyncTaskExecutor works well:

对于我们这里的目的,SimpleAsyncTaskExecutor效果不错。

@Configuration
public class AsynchronousSpringEventsConfig {
    @Bean(name = "applicationEventMulticaster")
    public ApplicationEventMulticaster simpleApplicationEventMulticaster() {
        SimpleApplicationEventMulticaster eventMulticaster =
          new SimpleApplicationEventMulticaster();
        
        eventMulticaster.setTaskExecutor(new SimpleAsyncTaskExecutor());
        return eventMulticaster;
    }
}

The event, the publisher and the listener implementations remain the same as before, but now the listener will asynchronously deal with the event in a separate thread.

事件、发布者和监听器的实现与以前一样,但现在监听器将在一个单独的线程中异步处理该事件。

4. Existing Framework Events

4.现有的框架事件

Spring itself publishes a variety of events out of the box. For example, the ApplicationContext will fire various framework events: ContextRefreshedEvent, ContextStartedEvent, RequestHandledEvent etc.

Spring本身发布了各种开箱即用的事件。例如,ApplicationContext将触发各种框架事件。ContextRefreshedEventContextStartedEventRequestHandledEvent等。

These events provide application developers an option to hook into the life cycle of the application and the context and add in their own custom logic where needed.

这些事件为应用程序开发人员提供了一个选择,使其能够钩住应用程序的生命周期和上下文,并在需要时加入自己的自定义逻辑。

Here’s a quick example of a listener listening for context refreshes:

下面是一个听众倾听上下文刷新的快速例子。

public class ContextRefreshedListener 
  implements ApplicationListener<ContextRefreshedEvent> {
    @Override
    public void onApplicationEvent(ContextRefreshedEvent cse) {
        System.out.println("Handling context re-freshed event. ");
    }
}

To learn more about existing framework events, have a look at our next tutorial here.

要了解更多关于现有框架事件的信息,请看我们的下一个教程

5. Annotation-Driven Event Listener

5.注释驱动的事件监听器

Starting with Spring 4.2, an event listener is not required to be a bean implementing the ApplicationListener interface — it can be registered on any public method of a managed bean via the @EventListener annotation:

从Spring 4.2开始,事件监听器不需要是实现ApplicationListener接口的Bean,它可以通过@EventListener注解在管理Bean的任何public方法上注册。

@Component
public class AnnotationDrivenEventListener {
    @EventListener
    public void handleContextStart(ContextStartedEvent cse) {
        System.out.println("Handling context started event.");
    }
}

As before, the method signature declares the event type it consumes.

和以前一样,该方法的签名声明了它所消耗的事件类型。

By default, the listener is invoked synchronously. However, we can easily make it asynchronous by adding an @Async annotation. We just need to remember to enable Async support in the application.

默认情况下,监听器是同步调用的。然而,我们可以通过添加@Async注解轻松地使其成为异步的。我们只需要记住在应用程序中启用Async支持

6. Generics Support

6.仿制药支持

It is also possible to dispatch events with generics information in the event type.

也可以用事件类型中的属相信息来调度事件。

6.1. A Generic Application Event

6.1.一个通用的应用程序事件

Let’s create a generic event type.

让我们创建一个通用的事件类型。

In our example, the event class holds any content and a success status indicator:

在我们的例子中,事件类持有任何内容和一个成功状态指示器。

public class GenericSpringEvent<T> {
    private T what;
    protected boolean success;

    public GenericSpringEvent(T what, boolean success) {
        this.what = what;
        this.success = success;
    }
    // ... standard getters
}

Notice the difference between GenericSpringEvent and CustomSpringEvent. We now have the flexibility to publish any arbitrary event and it’s not required to extend from ApplicationEvent anymore.

请注意GenericSpringEventCustomSpringEvent之间的区别。我们现在可以灵活地发布任何任意的事件,而且不需要再从ApplicationEvent扩展。

6.2. A Listener

6.2.一个听众

Now let’s create a listener of that event.

现在让我们创建该事件的监听器。

We could define the listener by implementing the ApplicationListener interface like before:

我们可以像以前一样通过实现 ApplicationListener接口来定义监听器。

@Component
public class GenericSpringEventListener 
  implements ApplicationListener<GenericSpringEvent<String>> {
    @Override
    public void onApplicationEvent(@NonNull GenericSpringEvent<String> event) {
        System.out.println("Received spring generic event - " + event.getWhat());
    }
}

But this definition unfortunately requires us to inherit GenericSpringEvent from the ApplicationEvent class. So for this tutorial, let’s make use of an annotation-driven event listener discussed previously.

但不幸的是,这个定义要求我们从ApplicationEvent类继承GenericSpringEvent。所以在本教程中,让我们利用前面讨论的注释驱动的事件监听器

It is also possible to make the event listener conditional by defining a boolean SpEL expression on the @EventListener annotation.

通过在@EventListener注解上定义一个布尔SpEL表达式,也可以使事件监听器成为有条件的

In this case, the event handler will only be invoked for a successful GenericSpringEvent of String:

在这种情况下,事件处理程序将只对GenericSpringEventString成功调用。

@Component
public class AnnotationDrivenEventListener {
    @EventListener(condition = "#event.success")
    public void handleSuccessful(GenericSpringEvent<String> event) {
        System.out.println("Handling generic event (conditional).");
    }
}

The Spring Expression Language (SpEL) is a powerful expression language that’s covered in detail in another tutorial.

Spring表达式语言(SpEL)是一种强大的表达式语言,在另一个教程中会详细介绍。

6.3. A Publisher

6.3.一个出版商

The event publisher is similar to the one described above. But due to type erasure, we need to publish an event that resolves the generics parameter we would filter on, for example, class GenericStringSpringEvent extends GenericSpringEvent<String>.

事件发布者与上面描述的类似。但是由于类型擦除,我们需要发布一个事件,解决我们要过滤的泛型参数,例如,class GenericStringSpringEvent extends GenericSpringEvent<String>

Also, there’s an alternative way of publishing events. If we return a non-null value from a method annotated with @EventListener as the result, Spring Framework will send that result as a new event for us. Moreover, we can publish multiple new events by returning them in a collection as the result of event processing.

此外,还有一种发布事件的替代方式。如果我们从注有@EventListener的方法中返回一个非空值作为结果,Spring Framework将把该结果作为一个新的事件为我们发送。此外,我们可以通过在一个集合中返回多个新事件作为事件处理的结果来发布这些事件。

7. Transaction-Bound Events

7.以事务为基础的事件

This section is about using the @TransactionalEventListener annotation. To learn more about transaction management, check out Transactions With Spring and JPA.

本节是关于使用@TransactionalEventListener注解。要了解有关事务管理的更多信息,请查看Transactions With Spring and JPA

Since Spring 4.2, the framework provides a new @TransactionalEventListener annotation, which is an extension of @EventListener, that allows binding the listener of an event to a phase of the transaction.

从Spring 4.2开始,框架提供了一个新的@TransactionalEventListener注解,它是@EventListener的扩展,可以将事件的监听器绑定到事务的某个阶段。

Binding is possible to the following transaction phases:

与以下交易阶段的绑定是可能的。

  • AFTER_COMMIT (default) is used to fire the event if the transaction has completed successfully.
  • AFTER_ROLLBACK – if the transaction has rolled back
  • AFTER_COMPLETION – if the transaction has completed (an alias for AFTER_COMMIT and AFTER_ROLLBACK)
  • BEFORE_COMMIT is used to fire the event right before transaction commit.

Here’s a quick example of a transactional event listener:

下面是一个事务性事件监听器的快速例子。

@TransactionalEventListener(phase = TransactionPhase.BEFORE_COMMIT)
public void handleCustom(CustomSpringEvent event) {
    System.out.println("Handling event inside a transaction BEFORE COMMIT.");
}

This listener will be invoked only if there’s a transaction in which the event producer is running and it’s about to be committed.

这个监听器只有在事件生产者正在运行的事务中并且即将提交时才会被调用。

And if no transaction is running, the event isn’t sent at all unless we override this by setting fallbackExecution attribute to true.

如果没有事务在运行,事件根本不会被发送,除非我们通过设置fallbackExecution属性为true来重写。

8. Conclusion

8.结论

In this quick article, we went over the basics of dealing with events in Spring, including creating a simple custom event, publishing it and then handling it in a listener.

在这篇快速文章中,我们介绍了在Spring中处理事件的基础知识,包括创建一个简单的自定义事件,发布它,然后在一个监听器中处理它。

We also had a brief look at how to enable the asynchronous processing of events in the configuration.

我们还简单看了一下如何在配置中启用事件的异步处理。

Then we learned about improvements introduced in Spring 4.2, such as annotation-driven listeners, better generics support and events binding to transaction phases.

然后我们了解了Spring 4.2中引入的改进,如注解驱动的监听器、更好的泛型支持和事件绑定到事务阶段。

As always, the code presented in this article is available over on GitHub. This is a Maven-based project, so it should be easy to import and run as it is.

像往常一样,本文介绍的代码可以在GitHub上找到over。这是一个基于Maven的项目,所以应该很容易导入并按原样运行。