How do I access command line arguments in a spring bean?

Question: How can I access varargs

the start method inside 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]

+7


source to share


3 answers


Analyzing the spring source code, it seems that spring is registering a singleton bean of type ApplicationArguments

in a prepareContext

class methodSpringApplication

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

      



So, I think you can autoincrement this bean in your service:

@Component
public MyService {

      @Autowired
      private ApplicationArguments  applicationArguments;

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

      }
}

      

+10


source


Thanks to @pvpkiran's tip:



@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;
    }
}

      

+3


source


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

      

+1


source







All Articles