java - Spring Boot - 在应用程序启动期间/之前运行代码的正确方法?

标签 java spring spring-boot spring-mvc

关于在启动时在 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,所以不确定是否有更简洁或更合适的方法来解决这个问题。

最佳答案

ApplicationRunnerCommandLineRunner 是执行需要在启动时注入(inject)依赖项的业务逻辑的正确接口(interface)。 两者之间没有太大区别。

CommandLineRunner 将使您能够访问启动时传递的原始 String 参数数组。
ApplicationRunner 会给你一个更结构化的 ApplicationArguments,但仅此而已。

您可以拥有多个启动运行者,甚至可以订购它们。


This seems hackish

不,不是。 ApplicationRunnerCommandLineRunner 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/

相关文章:

java - 从 Ruby 脚本执行 Ruby Gem

spring - 如何控制 Spring Hateoas 生成链接的 web 上下文?

java - Spring 集成 : error-channel - Problems with exception handling

java - 避免等待终止的线程

java - OpenCV 构建到 java,不在构建中生成 java 文件夹

java - 无法在 java Spring Boot 中创建新实体。获取 `` ` 无法启动嵌入式容器 ``` 错误

spring-boot - 带有 jwt 的 Spring Security oauth2,撤销刷新 token

java - Spring MySQL Profiler 抛出异常

java - 集合抛出 UnsupportedOperationException

spring - Spring Data Elasticsearch Repository查询定义日期输入参数格式