springboot自定义回调
时间: 2023-09-25 07:09:25 浏览: 46
在 Spring Boot 中,可以通过自定义回调函数来实现在应用程序启动或停止时执行特定的操作。
首先,需要实现 `ApplicationRunner` 或 `CommandLineRunner` 接口,并实现其 `run` 方法。`ApplicationRunner` 接口提供了一个 `ApplicationArguments` 参数,可以获取应用程序启动时传递的参数。而 `CommandLineRunner` 接口则提供了一个字符串数组参数,可以获取命令行参数。
例如,下面是一个实现 `ApplicationRunner` 接口的示例:
```java
@Component
public class MyApplicationRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
// 在应用程序启动时执行的操作
System.out.println("Application started with arguments: " + args);
}
}
```
或者,下面是一个实现 `CommandLineRunner` 接口的示例:
```java
@Component
public class MyCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
// 在应用程序启动时执行的操作
System.out.println("Application started with arguments: " + Arrays.toString(args));
}
}
```
这些自定义回调函数将在 Spring Boot 应用程序启动时自动执行。如果需要在应用程序停止时执行操作,可以使用 `@PreDestroy` 注解标记一个方法,它将在 Spring 容器关闭之前执行。
例如,下面是一个在应用程序停止时执行操作的示例:
```java
@Component
public class MyShutdownHook {
@PreDestroy
public void onShutdown() throws Exception {
// 在应用程序停止时执行的操作
System.out.println("Application stopped");
}
}
```
这些自定义回调函数可以帮助您在 Spring Boot 应用程序启动或停止时执行特定的操作。