springboot如何初始化时运行一段代码
时间: 2023-06-05 09:08:29 浏览: 65
Spring Boot提供了通过实现接口CommandLineRunner和ApplicationRunner来在Spring Boot应用程序启动时运行特定代码的机制。实现这些接口的类将在Spring应用程序启动时自动调用run方法。以下是一个简单的示例:
实现CommandLineRunner接口:
```
@Component
public class MyCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
// 这里写你想要初始化的代码
System.out.println("Hello, CommandLineRunner!");
}
}
```
实现ApplicationRunner接口:
```
@Component
public class MyApplicationRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
// 这里写你想要初始化的代码
System.out.println("Hello, ApplicationRunner!");
}
}
```
这些实现类需要被声明为组件,以便Spring Boot能够自动发现并执行它们的run方法。现在,当Spring Boot应用程序启动时,两个类的run方法将被调用,并输出"Hello, CommandLineRunner!"和"Hello, ApplicationRunner!"的信息。