SpringBoot2.x基础篇:应用程序在启动时访问启动项参数

Stella981
• 阅读 445

SpringBoot2.x基础篇:应用程序在启动时访问启动项参数

知识改变命运,撸码使我快乐,2020继续游走在开源界
点赞再看,养成习惯
给我来个Star吧,点击了解下基于SpringBoot的组件化接口服务落地解决方案

SpringBoot应用程序在启动时,我们可以传递自定义的参数来进行动态控制逻辑,比如我们使用--debug启动参数时就会使用debug启动应用程序,在控制台打印一些调试日志信息。

推荐阅读

什么是启动项参数?

启动项参数的格式一般是--开头的,如:java -jar service.jar --debug --skip,启动时我们就可以获取[debug,skip]两个启动项参数。

SpringBoot 内部提供了一个接口org.springframework.boot.ApplicationArguments来接收应用程序在启动时所传递的选项参数(Option Args),源码如下所示:

public interface ApplicationArguments {

    /**
     * 返回未处理的原始参数列表
     * @return the arguments
     */
    String[] getSourceArgs();

    /**
     * 返回所有选项参数的名称 
     * For example, if the arguments were
     * "--foo=bar --debug" would return the values {@code ["foo", "debug"]}.
     * @return the option names or an empty set
     */
    Set<String> getOptionNames();

    /**
     * 根据选项参数名称判断是否在启动时传递
     * option with the given name.
     * @param name the name to check
     * @return {@code true} if the arguments contain an option with the given name
     */
    boolean containsOption(String name);

    /**
     * 返回与具有给定名称的arguments选项关联的值的集合。
     * <ul>
     * <li>if the option is present and has no argument (e.g.: "--foo"), return an empty
     * collection ({@code []})</li>
     * <li>if the option is present and has a single value (e.g. "--foo=bar"), return a
     * collection having one element ({@code ["bar"]})</li>
     * <li>if the option is present and has multiple values (e.g. "--foo=bar --foo=baz"),
     * return a collection having elements for each value ({@code ["bar", "baz"]})</li>
     * <li>if the option is not present, return {@code null}</li>
     * </ul>
     * @param name the name of the option
     * @return a list of option values for the given name
     */
    List<String> getOptionValues(String name);

    /**
     * 返回分析的非选项参数的集合。
     * @return the non-option arguments or an empty list
     */
    List<String> getNonOptionArgs();
}

该接口有一个默认的实现DefaultApplicationArguments,它实现了ApplicationArguments接口的全部定义方法。

DefaultApplicationArguments类在org.springframework.boot.SpringApplication#run(java.lang.String...)方法内通过new进行实例化,该对象实例主要用于启动时的相关配置。

而在启动过程中的org.springframework.boot.SpringApplication#prepareContext方法内通过ConfigurableListableBeanFactory进行注册到IOC容器,并且把springApplicationArguments作为唯一名称。

获取启动项参数

上面我们说道,在应用启动时会将ApplicationArguments接口的实现类实例注册到IOC容器,所以我们可以使用注入ApplicationArguments接口的形式来获取启动项参数,如下所示:

/**
 * 加载启动项参数
 *
 * @author 恒宇少年
 */
@Component
public class LoadArguments {
    /**
     * 构造函数注入{@link ApplicationArguments}
     *
     * @param applicationArguments
     */
    @Autowired
    public LoadArguments(ApplicationArguments applicationArguments) {
        // 判断是否存在名为skip的启动项参数 
        boolean isHaveSkip = applicationArguments.containsOption("skip");
        System.out.println("skip:" + isHaveSkip);
        // 遍历输出全部的非启动项参数
        List<String> arguments = applicationArguments.getNonOptionArgs();
        for (int i = 0; i < arguments.size(); i++) {
            System.out.println("非启动项参数:" + arguments.get(i));
        }
    }
}

我们把项目通过mvn package命令进行打包后,使用如下命令启动:

java -jar spring-boot-basic-accessing-application-arguments-0.0.1-SNAPSHOT.jar --skip noway

当我们启动后控制台会输出如下内容:

...
skip:true
非启动项参数:noway
...

其中--skip为启动项参数,而后面携带的noway其实是不属于skip启动参数,如果我们使用--skip=noway作为启动参数时,调用ApplicationArguments#getOptionValues("skip")方法获取到的值则是noway

ApplicationRunner

除了通过注入ApplicationArguments的方式获取启动参数外,通过实现ApplicationRunner接口也可以获取ApplicationArguments对象实例,使用方法如下所示:

/**
 * {@link ApplicationRunner} 实现类
 *
 * @author 恒宇少年
 */
@Component
public class ApplicationRunnerSupport implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        boolean isHaveSkip = args.containsOption("skip");
        System.out.println("skip:" + isHaveSkip);
        System.out.println(args.getOptionValues("skip"));
    }
}

注意事项:实现ApplicationRunner接口的类需要通过@Component标注,通过注解方式注册到IOC容器。

敲黑板,划重点

我们可以通过注入ApplicationRunner这两种方法来获取ApplicationArguments对象,那你知道这两种方法的执行先后顺序吗?带着这个疑问可以动手实验下。

代码示例

如果您喜欢本篇文章请为源码仓库点个Star,谢谢!!! 本篇文章示例源码可以通过以下途径获取,目录为spring-boot-basic-accessing-application-arguments

作者个人 博客 使用开源框架 ApiBoot 助你成为Api接口服务架构师

点赞
收藏
评论区
推荐文章
Easter79 Easter79
2年前
SpringBoot2.x基础篇:编写应用程序时常用的ApplicationEvents
!(https://oscimg.oschina.net/oscnet/up98cf371fa7fc0208adc1e184465cd0efc82.png)知识改变命运,撸码使我快乐,2020继续游走在开源界<br/点赞再看,养成习惯<br/给我来个Star吧,点击了解下基于SpringBoot的组件化接口服务落地解决方案(http
Stella981 Stella981
2年前
SpringBoot2.x基础篇:带你了解扫描Package自动注册Bean
!(https://oscimg.oschina.net/oscnet/up6d27eb9793200379ece2b49fc26ed46ef74.png)知识改变命运,撸码使我快乐,2020继续游走在开源界<br/点赞再看,养成习惯<br/给我来个Star吧,点击了解下基于SpringBoot的组件化接口服务落地解决方案(http
Stella981 Stella981
2年前
SpringBoot2.x基础篇:Linux后台运行Jar以及Jvm参数调优
!(https://oscimg.oschina.net/oscnet/upc5c9362401c5627495b4406279f3ce4b79a.png)知识改变命运,撸码使我快乐,2020继续游走在开源界<br/点赞再看,养成习惯<br/给我来个Star吧,点击了解下基于SpringBoot的组件化接口服务落地解决方案(http
Stella981 Stella981
2年前
SpringBoot2.x基础篇:将应用程序打包为可执行Jar
!(https://oscimg.oschina.net/oscnet/up991592576a2fa63c72e03fc287acfa0d469.png)知识改变命运,撸码使我快乐,2020继续游走在开源界<br/点赞再看,养成习惯<br/给我来个Star吧,点击了解下基于SpringBoot的组件化接口服务落地解决方案(http
Stella981 Stella981
2年前
SpringBoot2.x基础篇:编写应用程序时常用的ApplicationEvents
!(https://oscimg.oschina.net/oscnet/up98cf371fa7fc0208adc1e184465cd0efc82.png)知识改变命运,撸码使我快乐,2020继续游走在开源界<br/点赞再看,养成习惯<br/给我来个Star吧,点击了解下基于SpringBoot的组件化接口服务落地解决方案(http
Easter79 Easter79
2年前
SpringBoot2.x基础篇:Linux后台运行Jar以及Jvm参数调优
!(https://oscimg.oschina.net/oscnet/upc5c9362401c5627495b4406279f3ce4b79a.png)知识改变命运,撸码使我快乐,2020继续游走在开源界<br/点赞再看,养成习惯<br/给我来个Star吧,点击了解下基于SpringBoot的组件化接口服务落地解决方案(http
Easter79 Easter79
2年前
SpringBoot2.x基础篇:带你了解扫描Package自动注册Bean
!(https://oscimg.oschina.net/oscnet/up6d27eb9793200379ece2b49fc26ed46ef74.png)知识改变命运,撸码使我快乐,2020继续游走在开源界<br/点赞再看,养成习惯<br/给我来个Star吧,点击了解下基于SpringBoot的组件化接口服务落地解决方案(http
Easter79 Easter79
2年前
SpringBoot2.x基础篇:应用程序在启动时访问启动项参数
!(https://oscimg.oschina.net/oscnet/up0fc757b29ab18ad630d891e2e83eb81fea4.png)知识改变命运,撸码使我快乐,2020继续游走在开源界<br/点赞再看,养成习惯<br/给我来个Star吧,点击了解下基于SpringBoot的组件化接口服务落地解决方案(http
Stella981 Stella981
2年前
SpringBoot发布了新年版本,v2.2.3发布
!(https://oscimg.oschina.net/oscnet/upadce5247275606cf970bc4e580eec489381.png)知识改变命运,撸码使我快乐,2020继续游走在开源界<br/点赞再看,养成习惯<br/给我来个Star吧,点击了解下基于SpringBoot的组件化接口服务落地解决方案(http
Easter79 Easter79
2年前
SpringBoot发布了新年版本,v2.2.3发布
!(https://oscimg.oschina.net/oscnet/upadce5247275606cf970bc4e580eec489381.png)知识改变命运,撸码使我快乐,2020继续游走在开源界<br/点赞再看,养成习惯<br/给我来个Star吧,点击了解下基于SpringBoot的组件化接口服务落地解决方案(http