문제

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 EventReceiver {

    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 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

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top