关于在启动时在 Spring Boot Web 应用程序中实现逻辑似乎存在不同意见。但是没有就“最佳实践”或优于其他方法的首选方法等达成共识。
我有以下代码在启动时实现 ApplicationRunner 接口(interface)(带有一些虚拟输出):
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
@Component
@Slf4j
public class AppStartupRunner implements ApplicationRunner {
public static int counter;
@Override
public void run(ApplicationArguments args) throws Exception {
log.info("Application started with option names : {}",
args.getOptionNames());
log.info("Increment counter");
counter++;
}
}
这种方法是否被认为是“适当的”(因为没有更好的术语)?我的意图是运行一些代码以在启动时从数据库中获取值,将它们存储在使用 Ehcache 和其他一些“初始化”位中。
这似乎hackish,所以不确定是否有更简洁或更合适的方法来解决这个问题。
最佳答案
ApplicationRunner
和 CommandLineRunner
是执行需要在启动时注入(inject)依赖项的业务逻辑的正确接口(interface)。
两者之间没有太大区别。
CommandLineRunner
将使您能够访问启动时传递的原始 String
参数数组。
ApplicationRunner
会给你一个更结构化的 ApplicationArguments
,但仅此而已。
您可以拥有多个启动运行者,甚至可以订购它们。
This seems hackish
不,不是。 ApplicationRunner
和 CommandLineRunner
JavaDoc
Interface used to indicate that a bean should run when it is contained within a
SpringApplication
.
关于java - Spring Boot - 在应用程序启动期间/之前运行代码的正确方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55425494/