SpringBoot通过ApplicationArguments获取args

如果你需要获取通过SpringApplication.run(…​)传输过来的arguments,可以直接注入一个ApplicationArguments即可实现,如下面这个例子:

@Service
public class ApplicationArgumentService {

    private final ApplicationArguments applicationArguments;

    @Autowired
    public ApplicationArgumentService(ApplicationArguments applicationArguments) {
        this.applicationArguments = applicationArguments;
        for (String sourceArg : applicationArguments.getSourceArgs()) {
            System.out.println(sourceArg);
        }
        for (String optionName : applicationArguments.getOptionNames()) {
            System.out.println(optionName + " = " + applicationArguments.getOptionValues(optionName));
        }
    }

}

 当然,要注意的是SpringBoot的启动类中,在执行run方法的时候参数不能为空(标红部分):

@SpringBootApplication
public class SpringBootTestApplication {

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

 

posted @ 2018-11-01 17:35  柚子苹果果  阅读(4088)  评论(0编辑  收藏  举报