简体   繁体   English

如何在运行 Java jar 文件时进行参数覆盖?

[英]How to make a parameter override while running a Java jar file?

I have a Java maven project whose Jar file is used as a SDK library in other projects.我有一个 Java maven 项目,其 Jar 文件在其他项目中用作 ZF20E3C5E54C0AB3D36AZAZ8D6 库This SDK is used to call other APIs which are by default in the prod environment.这个 SDK 用于调用 prod 环境中默认的其他 API。 I want to make it run on testing environment by overriding a variable.我想通过覆盖一个变量让它在测试环境中运行。

public class Routes {

    public Map<String, String> routes;
    private static String _baseUrl = "https://production-env.com";

    @SuppressWarnings("serial")
    public Routes() {
        routes = new HashMap<String, String>() {
            {
                put("api.login", "/rest/login");
                put("api.register", "/rest/register");

            }
        };
    }
}

This is the Routes class which contains the base URL for prod/testing is used by other classes.这是路线 class ,其中包含基础 URL 用于生产/测试,其他类使用。 I want to have the default _baseUrl as the same one as above.我想让默认的_baseUrl与上面的相同。 But I want to be able to override it to "https://testing-env.com" while running the Jar.但我希望能够在运行 Jar 时将其覆盖为"https://testing-env.com" And I don't want to add a public setter for that.而且我不想为此添加一个公共设置器。 I want to be able to do so by passing some arguments while running the Jar file.我希望能够通过在运行 Jar 文件时传递一些 arguments 来做到这一点。

As @Thomas mentioned in comment:正如@Thomas 在评论中提到的:

// Get system property with default if property does not exist
public class Routes {

    private static String _baseUrl = System.getProperty("base.url", "https://production-env.com");

    public Map<String, String> routes;
    
    @SuppressWarnings("serial")
    public Routes() {
        routes = new HashMap<String, String>() {
            {
                put("api.login", "/rest/login");
                put("api.register", "/rest/register");

            }
        };
    }
}

Set property when executing jar执行 jar 时设置属性

java -Dbase.url=https://dev-env.com -jar my.jar

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM