spring boot 项目启动调用方法
时间: 2023-07-29 09:14:51 浏览: 59
在 Spring Boot 项目启动时,可以通过实现 CommandLineRunner 或 ApplicationRunner 接口来定义需要在启动时自动执行的方法。这两个接口都只有一个 run 方法,该方法会在 Spring Boot 应用启动完成后自动执行。
例如,实现 CommandLineRunner 接口的示例代码如下:
```java
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class MyCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
// 在这里编写需要在启动时执行的代码
System.out.println("Spring Boot 应用启动完成!");
}
}
```
在这个示例中,我们通过 @Component 注解将 MyCommandLineRunner 类注册为一个 Spring Bean,并实现 CommandLineRunner 接口。在 run 方法中,我们可以编写需要在启动时执行的代码,例如打印一条启动完成的消息。
除了 CommandLineRunner 和 ApplicationRunner 接口,还可以通过 @PostConstruct 注解来标注一个方法,在 Spring Bean 初始化完成后自动执行。这种方式适用于需要在应用启动前执行的代码,例如初始化一些配置信息等。