ApplicationListener 实现
时间: 2025-02-21 09:47:05 浏览: 36
### 如何实现 `ApplicationListener` 并创建示例
在 Spring Boot 中,`ApplicationListener` 提供了一种机制来响应应用上下文中发生的事件。这使得开发者能够在特定的时间点执行自定义逻辑。
#### 创建一个简单的 `ApplicationListener`
为了展示如何使用 `ApplicationListener`,下面是一个完整的例子,展示了如何监听并处理 `ContextRefreshedEvent` 事件:
```java
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
@Component
public class MyApplicationListener implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
System.out.println("ApplicationContext has been initialized or refreshed");
}
}
```
这段代码实现了 `ApplicationListener` 接口,并指定了要监听的具体事件类型——这里是 `ContextRefreshedEvent`[^2]。每当 Spring 容器刷新或初始化时,就会触发此方法中的逻辑。
对于更复杂的场景,还可以利用泛型参数化的方式让同一个监听器能够应对多种类型的事件。例如:
```java
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
@Component
public class MultiEventListener implements ApplicationListener<ApplicationEvent> {
@Override
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof ContextRefreshedEvent) {
handleContextRefresh((ContextRefreshedEvent) event);
} else if (event instanceof ContextStartedEvent) {
handleContextStart((ContextStartedEvent) event);
}
// Add more conditions as needed...
}
private void handleContextRefresh(ContextRefreshedEvent event){
System.out.println("Handling context refresh...");
}
private void handleContextStart(ContextStartedEvent event){
System.out.println("Handling context start...");
}
}
```
上述多事件处理器不仅限于监听单一类型的事件,而是可以根据传入的不同事件实例采取不同的行动[^3]。
阅读全文
相关推荐


















