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.

1 Answers

2
Steve On Best Solutions

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]