温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Spring Boot中怎么通过ApplicationArguments获取args参数

发布时间:2021-06-22 17:05:29 来源:亿速云 阅读:1205 作者:Leah 栏目:编程语言

本篇文章给大家分享的是有关Spring Boot中怎么通过ApplicationArguments获取args参数,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

1,直接使用new DefaultApplicationArguments( args)进行转换。

public ConfigurableApplicationContext run(String... args) {
    // 下面的内容,封装String... args成 ApplicationArguments
}
// 将参数封装到ApplicationArguments对象中
ApplicationArguments applicationArguments = new DefaultApplicationArguments( args);

在具体使用Spring Boot的过程中,如果需要获得SpringApplication.run(args)方法传递的参数,那么可通过ApplicationArguments接口来获得。

2,使用方法非常简单,只用在需要获得参数的类中直接注入ApplicationArguments即可。

如下代码:

@Component
public class ArgsBean {

	@Resource
	private ApplicationArguments arguments;

	public void printArgs() {
		System.out.println("# 非选项参数数量: " + arguments.getNonOptionArgs().size());
		System.out.println("# 选项参数数量: " + arguments.getOptionNames().size());
		System.out.println("# 非选项参具参数:");
		arguments.getNonOptionArgs().forEach(System.out::println);

		System.out.println("# 选项参数具体参数:");
		arguments.getOptionNames().forEach(optionName -> {
			System.out.println("--" + optionName + "=" + arguments.getOptionValues(optionName));
		});
	}

}

3,还有一种是springboot的Application实现了ApplicationRunner这个接口。

package com.imddysc.testc;

import java.util.Iterator;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;

import com.imddysc.testc.util.SpringContextUtils;

@SpringBootApplication
public class Application2 implements ApplicationRunner {
	
	private static final Logger logger = LoggerFactory.getLogger(Application2.class);
	
	@Autowired
	private static SpringContextUtils springContextUtils;

	public static void main(String[] args) throws Exception {
		new SpringApplicationBuilder(Application2.class).web(WebApplicationType.NONE) // .REACTIVE, .SERVLET
		.run(args);
		logger.info("启动完成!");
	}

	@Override
	public void run(ApplicationArguments args) throws Exception {
		logger.info("spring boot not web!!! SpringBoot Application Runner ... ");
		
		HdfsHttp hdfsHttp = new HdfsHttp();
		hdfsHttp.getRandomIp();
		
		/** 默认参数 */
		String mkdir = "";  // --mkdir=upload/xxx/
		String put = "";  // --uploadfile=a.txt
		String get = "";  // --uploadNewFileName=aaa.txt
		String localfile = "";
		String descfile = "";
		String mkdirpath = "";
		
		/** 有帮助与否显示帮助 */
		Set<String> argsSet = args.getOptionNames();
		if (argsSet.isEmpty() || argsSet.contains("help")) {
			printHelp();
			System.exit(1);
		}
		
		/** 参数赋值 */
		if (!argsSet.isEmpty()) {
			for (Iterator iterator = argsSet.iterator(); iterator.hasNext();) {
				String arg = (String) iterator.next();
				if (arg.equalsIgnoreCase("localfile")) {
					localfile = args.getOptionValues("localfile").get(0);
				}
				if (arg.equalsIgnoreCase("descfile")) {
					descfile = args.getOptionValues("descfile").get(0);
				}
				if (arg.equalsIgnoreCase("mkdirpath")) {
					mkdirpath = args.getOptionValues("mkdirpath").get(0);
				}
			}
		}
		/** 处理--mkdir */
		if (argsSet.contains("mkdir")) {
			logger.info("mkdirpath: " + mkdirpath);
			if (mkdirpath.isEmpty() || mkdirpath.length() == 0) {
				logger.info("mkdirpath参数为空!");
				System.exit(1);
			}
			HdfsFile hdfsFile = new HdfsFile();
			hdfsFile.mkdir(mkdirpath);
			System.exit(1);
		}
		/** 处理--put */
		if (argsSet.contains("put")) {
			logger.info("localfile: " + localfile);
			logger.info("descfile: " + descfile);
			if (localfile.isEmpty() || localfile.length() == 0 || descfile.isEmpty() || descfile.length() == 0) {
				logger.info("localfile参数为空,或者descfile参数为空!");
				System.exit(1);
			}
			HdfsFile hdfsFile = new HdfsFile();
			hdfsFile.putFile(localfile, descfile);
			System.exit(1);
		}
		/** 处理--get */
		if (argsSet.contains("get")) {
			logger.info("descfile: " + descfile);
			logger.info("localfile: " + localfile);
			if (localfile.isEmpty() || localfile.length() == 0 || descfile.isEmpty() || descfile.length() == 0) {
				logger.info("localfile参数为空,或者descfile参数为空!");
				System.exit(1);
			}
			HdfsFile hdfsFile = new HdfsFile();
			hdfsFile.getFile(descfile, localfile);
			System.exit(1);
		}
		
	}
	
	public static void printHelp() {
		System.out.println("--mkdir --mkdirpath=要创建的路径");
		System.out.println("--put --localfile=要上传的文件, --descfile=上传的目录(远端)");
		System.out.println("--get --descfile=要下载的文件, --localfile下载的目录(本地)");
		System.out.println("--get --descfile=cloud/a.txt --localfile=E:/codes/");
	}

}

4,提到了ApplicationRunner 再提提CommandLineRunner。

看一下CommandLineRunner和ApplicationRunner的源代码

public interface CommandLineRunner {

	/**
	 * Callback used to run the bean.
	 * @param args incoming main method arguments
	 * @throws Exception on error
	 */
	void run(String... args) throws Exception;

}
public interface ApplicationRunner {

	/**
	 * Callback used to run the bean.
	 * @param args incoming application arguments
	 * @throws Exception on error
	 */
	void run(ApplicationArguments args) throws Exception;

}

它们唯一不同便是run方法的参数 。

通过接口的官方文档,我们得知其实执行CommandLineRunner和ApplicationRunner的实现类是有顺序的,只不过在示例中并没有展示。针对上面的示例,我们可以通过@Order或实现Ordered接口来对其指定执行顺序。

第二部分:常见API介绍

获取对应的有选项的选项名称集合
Set<String> getOptionNames()

判断是否包含某个选项名称否
boolean containsOption(String name)

根据选项名称返回一个选项值列表
List<String> getOptionValues(String name)

返回非选项值列表
List<String> getNonOptionArgs()

返回源参数字符串数组
String[] getSourceArgs()

以上就是Spring Boot中怎么通过ApplicationArguments获取args参数,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI