membersound
membersound

Reputation: 86845

How to access command line args in a spring bean?

Question: how can I access the varargs of the startup method inside a spring @Bean like MyService below?

@SpringBootApplication
public class MyApp {
    public static void main(String[] args) {
        SpringApplication.run(MyApp.class, args);
    }
}

@Component
public MyService {
       public void run() {
               //read varargs
       }
}

java -jar [jarfile] [Command Line Arguments]

Upvotes: 8

Views: 3868

Answers (3)

Sucheth Shivakumar
Sucheth Shivakumar

Reputation: 447

@Configuration
public class CheckArguments {

    private ApplicationArguments applicationArguments;

    CheckArguments(ApplicationArguments applicationArguments) {
        this.applicationArguments = applicationArguments;
    }

    public void printArguments(){
        for(String arg : applicationArguments.getSourceArgs()){
            System.out.println(arg);
        }
    }
}

Upvotes: 4

membersound
membersound

Reputation: 86845

Thanks to the hint of @pvpkiran:

@Component
public class CommandLineHolder implements CommandLineRunner {
    private String[] args;

    @Override
    public void run(String... args) throws Exception {
        this.args = args;
    }

    public String[] getArgs() {
        return args;
    }
}

Upvotes: 4

Olivier Boissé
Olivier Boissé

Reputation: 18143

By analyzing spring source code, it seems that spring registers a singleton bean of type ApplicationArguments in the method prepareContext of the class SpringApplication

context.getBeanFactory().registerSingleton("springApplicationArguments",
            applicationArguments);

So I think you can autowire this bean in your service :

@Component
public MyService {

      @Autowired
      private ApplicationArguments  applicationArguments;

      public void run() {
             //read varargs
             applicationArguments.getSourceArgs();

      }
}

Upvotes: 12

Related Questions