ApplicationEventPublisher event that does?

1

The event:

@Autowired
private ApplicationEventPublisher publisher;

send:

eventPublisher.publish(new CreateParticipantEvent(conversation, participant));

Do you send notifications to everyone? How does it work?

    
asked by deluf 08.05.2017 в 23:23
source

1 answer

1

Allows you to post events that can be received by listeners configured for it.

You can use the events published by the framework or customized, to launch your own events you need 4 parts:

Configuration

Declare the publisher in the web.xml so you can publish events in the context of the application.

<listener>
    <listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
</listener>

Event

Class that must inherit from ApplicationEvent , in your case CreateParticipantEvent . For example:

public class CreateParticipantEvent extends ApplicationEvent {

  private Object conversation;
  private Object participant;

  public CreateParticipantEventextends (Object conversation, Object participant) {

    super();
    this.conversation = conversation;
    this.participant= participant;
  }

  //GETTERS, TOSTRING...

}

You can also use existing events, such as HttpSessionDestroyedEvent .

Publisher

The person in charge of "throwing" those events, in this case the origin of your question. For example:

public class CreateParticipantEventPublisher {

  @Autowired
  private ApplicationEventPublisher publisher;

  public Notify(Object conversation, Object participant) {

    eventPublisher.publish(new CreateParticipantEvent(conversation, participant));

  }

}

Listener

The person in charge of listening to certain events. For example,

public class CreateParticipantEventListener implements ApplicationListener<CreateParticipantEvent > {


  @Override
  public void onApplicationEvent(CreateParticipantEvent event) {

    System.out.println("Fired event: " + event);

  }

}

To use existing ones, you simply have to create a listener for them.

As additional information, I leave you here a resource (in English) with a guide of good practices for the publication of events.

    
answered by 09.05.2017 / 08:47
source