从 Spring Bean 访问命令行参数(在本例中为 ApplicationReadyEvent 侦听器) [英] Accessing command line arguments from Spring Beans (in this case, ApplicationReadyEvent listener)

查看:42
本文介绍了从 Spring Bean 访问命令行参数(在本例中为 ApplicationReadyEvent 侦听器)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个 Spring-Boot 应用程序,我们首先通过命令行传递一些参数.

We have a Spring-Boot application which we start by passing some arguments via the command line.

我们希望在收到 ApplicationReadyEvent 时访问这些参数,以便在应用程序启动时执行一些逻辑.

We want to access these arguments when we receive an ApplicationReadyEvent, to execute some logic at application startup.

我无法让它工作.尝试使用 @EventListener 注释甚至接口,但似乎没有任何效果.

I am not able to get that working. Tried with @EventListener annotation and even interface but nothing seems to be working.

推荐答案

我想您只是在问如何在事件侦听器中访问应用程序的命令行参数.为此,您只需通过其构造函数将 ApplicationArguments bean 注入您的侦听器对象,如下所示:

I think you're just asking how you can get access to the application's command line arguments inside of an event listener. To do that, you can just inject the ApplicationArguments bean into your listener object, via its constructor, like so:

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component
public class Ready implements ApplicationListener<ApplicationReadyEvent> {

    private ApplicationArguments appArgs;

    public Ready(ApplicationArguments appArgs) {
        this.appArgs = appArgs;
    }

    @Override
    public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
        System.out.println("App Args: " + Arrays.asList(appArgs.getSourceArgs()));
    }
}

一旦您拥有 ApplicationArguments 对象,您就可以通过 getSourceArgs() 方法以数组的形式访问命令行参数.我将数组变成了一个列表,以便正确打印.

Once you have the ApplicationArguments object, you can access the command line arguments as an array via the getSourceArgs() method. I turn the array into a list just so it will print correctly.

作为测试,我在启动时将三个参数 'a'、'b' 和 'c' 传递给我的应用程序,并在应用程序启动结束时打印此行:

As a test, I passed the three arguments 'a', 'b' and 'c' to my app at startup, and this line is printed at the end of app startup:

App Args: [a, b, c]

这篇关于从 Spring Bean 访问命令行参数(在本例中为 ApplicationReadyEvent 侦听器)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆