23.7 访问应用参数

如果需要获取传递给SpringApplication.run(…)的应用参数,你可以注入一个org.springframework.boot.ApplicationArguments类型的bean。ApplicationArguments接口即提供对原始String[]参数的访问,也提供对解析成optionnon-option参数的访问:

  1. import org.springframework.boot.*
  2. import org.springframework.beans.factory.annotation.*
  3. import org.springframework.stereotype.*
  4. @Component
  5. public class MyBean {
  6. @Autowired
  7. public MyBean(ApplicationArguments args) {
  8. boolean debug = args.containsOption("debug");
  9. List<String> files = args.getNonOptionArgs();
  10. // if run with "--debug logfile.txt" debug=true, files=["logfile.txt"]
  11. }
  12. }

Spring Boot也会注册一个包含Spring Environment属性的CommandLinePropertySource,这就允许你使用@Value注解注入单个的应用参数。