场景
获取java项目启动参数。
方法
除在主函数mian中的args中获取外,还可以通过注入Spring的ApplicationArguments获取,代码如下:
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Set;
/**
* LizzApp
*/
@SpringBootApplication
public class LizzApp {
@Autowired
private ApplicationArguments applicationArguments;
public static void main(String[] args) {
SpringApplication.run(LizzApp.class, args);
System.out.println("args:" + JSON.toJSONString(args));
}
@PostConstruct
public void getArgs() {
//获取所有program arguments参数
String[] sources = applicationArguments.getSourceArgs();
System.out.println("sources:" + JSON.toJSONString(sources));
// 获取其中--设置的参数名
Set<String> optionArgs = applicationArguments.getOptionNames();
System.out.println("optionArgs:" + JSON.toJSONString(optionArgs));
// 获取其中非--设置的参数
List<String> nonOptionArgs = applicationArguments.getNonOptionArgs();
System.out.println("nonOptionArgs:" + JSON.toJSONString(nonOptionArgs));
// 获取某参数值
List<String> values = applicationArguments.getOptionValues("spring.profiles.active");
System.out.println("values:" + JSON.toJSONString(values));
}
}
输出
sources:["--spring.profiles.active=dev,10000","a=b","-d=e,f"]
optionArgs:["spring.profiles.active"]
nonOptionArgs:["a=b","-d=e,f"]
values:["dev,10000"]
args:["--spring.profiles.active=dev,10000","a=b","-d=e,f"]