Câu hỏi phỏng vấn Spring
Câu hỏi

How is event handling done in Spring?

Câu trả lời

Event handling in Spring is a robust mechanism that allows different components of an application to communicate with each other through events, without being tightly coupled. This process is primarily managed through the ApplicationEvent class and the ApplicationListener interface, along with the use of annotations such as @EventListener. Here’s a detailed explanation of how event handling is structured in Spring:

ApplicationEvent Class

In Spring, events are typically subclasses of the ApplicationEvent class. This class stores the event details and provides them to the listeners when an event is published. An event can be anything from a change in the state of an application to user actions[1][2].

ApplicationListener Interface

Listeners that are interested in receiving these events must implement the ApplicationListener interface, which requires the definition of the onApplicationEvent method. This method is called when an event that the listener is registered for is published[3].

Using @EventListener Annotation

Since Spring 4.2, handling events has become more flexible and less boilerplate-heavy with the introduction of the @EventListener annotation. This annotation can be used on any public method of a bean to indicate that it should receive events of specific types. This method does not need to implement any specific interface, which simplifies the event handling code[2][6].

Publishing Events

Events are published using the ApplicationEventPublisher interface, which is typically injected into the beans that want to publish events. By calling the publishEvent method, a bean can publish an event to all registered listeners[1][10].

Asynchronous Event Handling

By default, event handling in Spring is synchronous, meaning the process that publishes the event must wait until all listeners have processed the event. However, Spring also supports asynchronous event handling. By using the @Async annotation along with @EventListener, you c...

junior

junior

Gợi ý câu hỏi phỏng vấn

middle

How to validate form data in Spring Web MVC Framework?

senior

What are some of the important Spring annotations you have used?

senior

How does Spring 5 integrate with JDK 9 modularity?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào