阅读量:126
Spring Boot 提供了 CommandLineRunner 和 ApplicationRunner 接口,用于在 Spring Boot 应用启动时执行一些任务。通过实现这些接口,可以在命令行环境中执行一些特定的逻辑。
以下是在 Spring Boot 中集成 CommandLineRunner 和 Web 环境的方式:
- 创建一个类实现 CommandLineRunner 接口,并实现 run 方法。在 run 方法中编写需要在应用启动时执行的逻辑。
@Component
public class MyCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("This is executed on application startup");
}
}
-
在该类上添加 @Component 注解,使其成为 Spring Bean。
-
创建一个 Spring Boot 应用类,并在启动类中添加 @SpringBootApplication 注解。
@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
- 在启动类中注入 CommandLineRunner 类,使其在应用启动时执行。
@Autowired
private MyCommandLineRunner myCommandLineRunner;
通过以上步骤,可以在 Spring Boot 应用启动时执行特定的逻辑。同时,在 Web 环境中也可以正常运行应用,并与 CommandLine 环境集成。