Subdomain 1.1: Introduction to Spring Framework
1.A user registration service in your Spring application needs to trigger an email notification and an audit log entry whenever a new user is created. To adhere to the Open/Closed Principle and avoid tightly coupling the registration service to the email and audit services, which Spring Framework feature should you utilize?
- A.Spring Expression Language (SpEL)
- B.ApplicationEventPublisher and @EventListener
- C.The Template Method pattern via JdbcTemplate
- D.BeanPostProcessor
Show answer & explanation
Correct answer: B — ApplicationEventPublisher and @EventListener
- A. Spring Expression Language (SpEL) is a powerful expression language used for querying and manipulating an object graph at runtime or for configuration. It is not designed for component decoupling or application-level event handling.
- B. ApplicationEventPublisher and @EventListener implement the Observer/Publisher-Subscriber pattern within the Spring context. This allows the registration service to publish an event without knowledge of the specific subscribers (email and audit services). This adheres to the Open/Closed Principle because new functionality (e.g., sending a welcome SMS) can be added by creating a new listener without modifying the existing registration service code.
- C. JdbcTemplate utilizes the Template Method pattern to simplify database access and manage resource cleanup (like closing connections). While it reduces boilerplate code, it does not provide a mechanism for service-to-service communication or event-driven decoupling.
- D. BeanPostProcessors are used by the Spring container to modify or wrap bean instances during their initialization phase (e.g., for creating proxies). They are part of the framework's lifecycle infrastructure, not for application-level business event propagation.