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

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

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

相关文章
|
2天前
|
前端开发 Java
SpringBoot之数组,集合,日期参数的详细解析
SpringBoot之数组,集合,日期参数的详细解析
14 0
|
2天前
|
Java 数据库连接 Spring
Spring Boot命令行启动添加参数
Spring Boot命令行启动添加参数
|
2天前
|
存储 JSON Java
SpringBoot集成AOP实现每个接口请求参数和返回参数并记录每个接口请求时间
SpringBoot集成AOP实现每个接口请求参数和返回参数并记录每个接口请求时间
48 2
|
2天前
|
缓存 Java Sentinel
Springboot 中使用 Redisson+AOP+自定义注解 实现访问限流与黑名单拦截
Springboot 中使用 Redisson+AOP+自定义注解 实现访问限流与黑名单拦截
|
2天前
|
Java 应用服务中间件 测试技术
深入探索Spring Boot Web应用源码及实战应用
【5月更文挑战第11天】本文将详细解析Spring Boot Web应用的源码架构,并通过一个实际案例,展示如何构建一个基于Spring Boot的Web应用。本文旨在帮助读者更好地理解Spring Boot的内部工作机制,以及如何利用这些机制优化自己的Web应用开发。
27 3
|
2天前
|
NoSQL Java Redis
springboot之RedisTemplate的访问单机,哨兵,集群模式
以上是配置RedisTemplate以连接到单机、哨兵和集群模式的示例。在实际应用中,还可以根据需求配置连接池、序列化方式、超时等其他参数。
36 0
|
2天前
|
Java Spring
spring boot访问接口报500
spring boot访问接口报500
13 2
|
2天前
|
前端开发 Java
SpringBoot之自定义注解参数校验
SpringBoot之自定义注解参数校验
19 2
|
2天前
|
Java 微服务 Spring
Spring Boot中获取配置参数的几种方法
Spring Boot中获取配置参数的几种方法
22 2
|
2天前
|
前端开发 JavaScript Java
SpringBoot解决跨域访问的问题
本文介绍了跨域访问的概念及其解决方案。同源策略规定浏览器限制不符合协议、Host和端口的请求,导致跨域访问被禁止。为解决此问题,文中提出了三种策略:1) 前端利用HTML标签的特性(如script、iframe)和JSONP、postMessage规避同源策略;2) 通过代理,如nginx或nodejs中间件,使得所有请求看似来自同一源;3) CORS(跨域资源共享),通过设置HTTP响应头允许特定跨域请求。在SpringBoot中,实现CORS有四种方式,包括使用CorsFilter、重写WebMvcConfigurer、CrossOrigin注解以及直接设置响应头。