SeamFramework.orgCommunity Documentation
Dependency injection enables loose-coupling by allowing the implementation of the injected bean type to vary, either a deployment time or runtime. Events go one step further, allowing beans to interact with no compile time dependency at all. Event producers raise events that are delivered to event observers by the container.
This basic schema might sound like the familiar observer/observable pattern, but there are a couple of twists:
不仅是事件产生者和观察者解耦;观察者和产生者也完全解耦,
observers can specify a combination of "selectors" to narrow the set of event notifications they will receive, and
observers can be notified immediately, or can specify that delivery of the event should be delayed until the end of the current transaction.
The CDI event notification facility uses more or less the same typesafe approach that we've already seen with the dependency injection service.
The event object carries state from producer to consumer. The event object is nothing more than an instance of a concrete Java class. (The only restriction is that an event type may not contain type variables). An event may be assigned qualifiers, which allows observers to distinguish it from other events of the same type. The qualifiers function like topic selectors, allowing an observer to narrow the set of events it observes.
An event qualifier is just a normal qualifier, defined using @Qualifier
. Here's an example:
@Qualifier
@Target({FIELD, PARAMETER})
@Retention(RUNTIME)
public @interface Updated {}
An observer method is a method of a bean with a parameter annotated @Observes
.
public void onAnyDocumentEvent(@Observes Document document) { ... }
The annotated parameter is called the event parameter. The type of the event parameter is the observed event type, in this case Document
. The event parameter may also specify qualifiers.
public void afterDocumentUpdate(@Observes @Updated Document document) { ... }
An observer method need not specify any event qualifiers—in this case it is interested in only unqualified events of a particular type. If it does specify qualifiers, it's only interested in events which have those qualifiers.
The observer method may have additional parameters, which are injection points:
public void afterDocumentUpdate(@Observes @Updated Document document, User user) { ... }
Event producers fire events using an instance of the parameterized Event
interface. An instance of this interface is obtained by injection:
@Inject @Any Event<Document
> documentEvent;
A producer raises events by calling the fire()
method of the Event
interface, passing the event object:
documentEvent.fire(document);
This particular event will be delivered to every observer method that:
has an event parameter to which the event object (the Document
) is assignable, and
specifies no qualifiers.
The container simply calls all the observer methods, passing the event object as the value of the event parameter. If any observer method throws an exception, the container stops calling observer methods, and the exception is rethrown by the fire()
method.
Qualifiers can be applied to an event in one of two ways:
by annotating the Event
injection point, or
by passing qualifiers to the select()
of Event
.
Specifying the qualifiers at the injection point is far simpler:
@Inject @Updated Event<Document
> documentUpdatedEvent;
Then, every event fired via this instance of Event
has the event qualifier @Updated
. The event is delivered to every observer method that:
有一个事件参数可以赋给事件对象,并且
does not have any event qualifier except for the event qualifiers that match those specified at the Event
injection point.
The downside of annotating the injection point is that we can't specify the qualifier dynamically. CDI lets us obtain a qualifier instance by subclassing the helper class AnnotationLiteral
. That way, we can pass the qualifier to the select()
method of Event
.
documentEvent.select(new AnnotationLiteral<Updated
>(){}).fire(document);
Events can have multiple event qualifiers, assembled using any combination of annotations at the Event
injection point and qualifier instances passed to the select()
method.
By default, if there is no instance of an observer in the current context, the container will instantiate the observer in order to deliver an event to it. This behavior isn't always desirable. We may want to deliver events only to instances of the observer that already exist in the current contexts.
A conditional observer is specified by adding receive = IF_EXISTS
to the @Observes
annotation.
public void refreshOnDocumentUpdate(@Observes(receive = IF_EXISTS) @Updated Document d) { ... }
A bean with scope @Dependent
cannot be a conditional observer, since it would never be called!
An event qualifier type may have annotation members:
@Qualifier
@Target({PARAMETER, FIELD})
@Retention(RUNTIME)
public @interface Role {
RoleType value();
}
成员值用来限制发送给观察者的消息:
public void adminLoggedIn(@Observes @Role(ADMIN) LoggedIn event) { ... }
Event qualifier type members may be specified statically by the event producer, via annotations at the event notifier injection point:
@Inject @Role(ADMIN) Event<LoggedIn
> loggedInEvent;
Alternatively, the value of the event qualifier type member may be determined dynamically by the event producer. We start by writing an abstract subclass of AnnotationLiteral
:
abstract class RoleBinding
extends AnnotationLiteral<Role
>
implements Role {}
The event producer passes an instance of this class to select()
:
documentEvent.select(new RoleBinding() {
public void value() { return user.getRole(); }
}).fire(document);
Event qualifier types may be combined, for example:
@Inject @Blog Event<Document
> blogEvent;
...
if (document.isBlog()) blogEvent.select(new AnnotationLiteral<Updated
>(){}).fire(document);
Observers must completely match the final qualified type of the event. Assume the following observers in this example:
public void afterBlogUpdate(@Observes @Updated @Blog Document document) { ... }
public void afterDocumentUpdate(@Observes @Updated Document document) { ... }
public void onAnyBlogEvent(@Observes @Blog Document document) { ... }
public void onAnyDocumentEvent(@Observes Document document) { ... }}}
The only observer notified will be:
public void afterBlogUpdate(@Observes @Updated @Blog Document document) { ... }
However, if there were also an observer:
public void afterBlogUpdate(@Observes @Any Document document) { ... }
It would also be notified, as @Any
acts as an alias for any and all qualifiers.
事务性的观察者在事件触发的事务完成阶段之前或者之后接收到事件通知。例如下面的观察者方法需要刷新在应用上下文中缓存的查询结果集,但只有在事务成果地更新了 Category
树之后才能发生:
public void refreshCategoryTree(@Observes(during = AFTER_SUCCESS) CategoryUpdateEvent event) { ... }
There are five kinds of transactional observers:
IN_PROGESS
observers are called immediately (default)
AFTER_SUCCESS
observers are called during the after completion phase of the transaction, but only if the transaction completes successfully
AFTER_FAILURE
observers are called during the after completion phase of the transaction, but only if the transaction fails to complete successfully
AFTER_COMPLETION
observers are called during the after completion phase of the transaction
BEFORE_COMPLETION
observers are called during the before completion phase of the transaction
Transactional observers are very important in a stateful object model because state is often held for longer than a single atomic transaction.
设想一下我们已经在应用范围内缓存了一个JPA的查询结果集:
@ApplicationScoped @Singleton
public class Catalog {
@PersistenceContext EntityManager em;
List<Product
> products;
@Produces @Catalog
List<Product
> getCatalog() {
if (products==null) {
products = em.createQuery("select p from Product p where p.deleted = false")
.getResultList();
}
return products;
}
}
一个 Product
时常会被创建或者删除。当这个动作发生后,我们需要刷新 Product
分类。但是我们需要在事务完全成功之后才能处理刷新。
The bean that creates and deletes Product
s could raise events, for example:
@Stateless
public class ProductManager {
@PersistenceContext EntityManager em;
@Inject @Any Event<Product
> productEvent;
public void delete(Product product) {
em.delete(product);
productEvent.select(new AnnotationLiteral<Deleted
>(){}).fire(product);
}
public void persist(Product product) {
em.persist(product);
productEvent.select(new AnnotationLiteral<Created
>(){}).fire(product);
}
...
}
现在 Catalog
能够观察到事务成功完成之后触发的事件:
@ApplicationScoped @Singleton
public class Catalog {
...
void addProduct(@Observes(during = AFTER_SUCCESS) @Created Product product) {
products.add(product);
}
void removeProduct(@Observes(during = AFTER_SUCCESS) @Deleted Product product) {
products.remove(product);
}
}