springboot使用监听器
时间: 2023-10-21 17:28:43 浏览: 103
在Spring Boot中使用监听器可以通过实现`ApplicationListener`接口来实现。下面是一个简单的示例:
首先,创建一个自定义监听器类,实现`ApplicationListener`接口,并指定监听的事件类型。例如,我们创建一个监听器类`MyEventListener`来监听`ApplicationStartedEvent`事件:
```java
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
public class MyEventListener implements ApplicationListener<ApplicationStartedEvent> {
@Override
public void onApplicationEvent(ApplicationStartedEvent event) {
System.out.println("应用程序已启动!");
// 在这里可以添加自定义的逻辑
}
}
```
然后,在Spring Boot应用程序的主类中注册监听器。可以使用`SpringApplication.addListeners()`方法来添加监听器:
```java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(MyApplication.class);
app.addListeners(new MyEventListener()); // 注册自定义监听器
app.run(args);
}
}
```
这样,在应用程序启动时,`MyEventListener`中的`onApplicationEvent()`方法就会被调用。
除了`ApplicationStartedEvent`,Spring Boot还提供了其他一些常用的事件,例如`ApplicationReadyEvent`、`ContextRefreshedEvent`等,你可以选择适合你需求的事件类型来监听。
希望以上信息能对你有帮助!如果还有其他问题,请随时提问。
阅读全文
相关推荐

















