简体   繁体   中英

Accessing command line arguments from Spring Beans (in this case, ApplicationReadyEvent listener)

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

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

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

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()));
    }
}

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.

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM