开发者

How JEE6 makes the link between Observer and Observee (Observer Pattern)

I've read some blog articles about Observer pattern implementation on JEE6 and something bother me... I can't find any information atm so i ask there...

I've found the following exemples:

@Stateless
[...]
public class ParisJugService {

   @Inject
   Event event;

   public void helloParis(){
        System.out.println("Hello Paris");
        event.fire("hello Paris invoked!");
   }
}

@Stateless
public class EventRece开发者_JAVA百科iver {

    public void onHelloParis(@Observes String message){
        System.out.println("----------- " + message);
    }
}

And

public class MyEvent {
    String data;
    Date eventTime;
    ....

}

public class EventProducer {

  @Inject @Any Event<MyEvent> event;


  public void doSomething() {
       MyEvent e=new MyEvent();
      e.data="This is a test event";
      e.eventTime=new Date();
      event.fire(e);

  }

}


public class EventConsumer {


    public void afterMyEvent(@Observes MyEvent event) {

        // .. Insert event logic here
    }

}

I can't understand how the link between event consumer and event producer is done...

Is it by naming convention of the methods? (Where the words "on", "after", "before"... will have sense)

Is it by comparison of given arguments (here String and MyEvent)?

I can't know and don't see what else could it be...


The container keeps metadata about all beans inside it. On startup it registers all observer methods together with the event type (the Class of the argument) they observe. Whenever an event is fired, the list of observers is checked for methods that accept the appropriate type of event.


The link between the event firing and the listener is based on the event type.

In your example:

public class EventConsumer {

    public void afterMyEvent(@Observes MyEvent event) {
        // .. Insert event logic here
    }

}

This class will receive all fired events of type MyEvent, wherever they come from.

Source: http://download-llnw.oracle.com/javaee/6/api/javax/enterprise/event/Observes.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜