我正在学习Spring boot。ApplicationRunner或任何运行器接口的一些典型用例是什么?
import org.junit.jupiter.api.Test;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class PersistencedemoApplicationTests implements ApplicationRunner {
@Test
void contextLoads() {
}
@Override
public void run(ApplicationArguments args) throws Exception {
// load initial data in test DB
}
}这是我知道的一个案例。还要别的吗?
发布于 2019-12-14 03:56:13
这些运行器用于在应用程序启动时运行逻辑,例如spring boot具有带有run方法的ApplicationRunner(功能接口
ApplicationRunner run()将在创建应用程序上下文之后和spring引导应用程序启动之前执行。
ApplicationRunner使用ApplicationArgument,它有像getOptionNames(),getOptionValues()和getSourceArgs()这样方便的方法。
同时CommandLineRunner也是一个带有run方法的函数接口
CommandLineRunner run()将在创建应用程序上下文之后和spring引导应用程序启动之前执行。
它接受在服务器启动时传递的参数。
它们都提供相同的功能,CommandLineRunner和ApplicationRunner之间唯一的区别是CommandLineRunner.run()接受String array[],而ApplicationRunner.run()接受ApplicationArguments作为参数。您可以在示例here中找到更多信息
发布于 2019-12-14 04:36:23
为了使用ApplicationRunner或CommandLineRunner接口,需要创建一个Spring bean并实现ApplicationRunner或CommandLineRunner接口,两者的性能相似。完成后,Spring应用程序将检测您的bean。
此外,还可以创建多个ApplicationRunner或CommandLineRunner beans,并通过实现以下两种方式之一来控制顺序
使用案例:
考虑一下:
@Component
public class MyBean implements CommandLineRunner {
@Override
public void run(String...args) throws Exception {
logger.info("App started with arguments: " + Arrays.toString(args));
}
}ApplicationRunner的详细信息
发布于 2021-11-27 04:01:09
ApplicationRunner和CommandLineRunner是Spring Boot提供的两个接口,用于在应用程序完全启动之前运行任何自定义代码。
Spring-batch是一个批处理框架。它使用CommandLineRunner在应用程序启动时注册和启动批处理作业。
您还可以使用此接口将一些基础数据加载到缓存中/执行健康检查。
应用程序的用例因应用程序而异。
https://stackoverflow.com/questions/59328583
复制相似问题