使用参数部署 *.war 文件

Deploy *.war file with parameters

我有一个使用 REST 的 Web 项目 API。我想在 tomcat 服务器上部署它的 5 个副本。例如:
test1.war => URL: http://localhost:8080/test1/api
test2.war => URL: http://localhost:8080/test2/api
test3.war => URL: http://localhost:8080/test3/api
...
问题是每个 war 文件应该使用不同的配置文件。我知道我可以使用 export CATALINA_OPTs="Dparam1=/usr/config1.txt" 设置环境变量。然后我需要更改每个 war 文件中的源代码,以便读取 test1.war 的 param1,test2.war 的 param2。但是每个 war 文件应该是相同的(只是名称不同)。理论上完美的解决方案是这样的:

    deploy test1.war -conf <path1>
    deploy test2.war -conf <path2>
    deploy test3.war -conf <path3>


是否可以在 tomcat 中进行?有其他替代方法吗?

我决定在 运行 时为应用程序获取适当的配置文件。

1)获取当前运行ningMainApp.class在war里面的路径(如warname.war) 文件包含这样的代码:

String path = MainApp.class.getProtectionDomain().getCodeSource().getLocation().getPath();
String decodedPath = java.net.URLDecoder.decode(path, "UTF-8");
// decodedPath - "D:/apache-tomcat-7.0.81/apache-tomcat-7.0.81/webapps/warname/WEB-INF/classes/com/gieseckedevrient/rsp/servertester/MainApp.class"


2) 解析此解码路径以仅获取“warname”:

String parentName = "";
java.io.File parentFile = null;
while (!"WEB-INF".equals(parentName)) {
  File file = new File(decodedPath);
  parentFile = file.getParentFile();
  parentName = parentFile.getName();
  decodedPath = parentFile.getAbsolutePath();               
  }
String realWarName = parentFile.getParentFile().getName();


3) 在 TOMCAT_HOME}/bin/ 中创建文件 "setenv.bat" 并在其中插入此代码 (warname.config.file warname.warwarname2.config.file warname2.war):

set CATALINA_OPTS=-Dwarname.config.file=D:\app.properties -Dwarname2.config.file=D:\app2.properties


4) 使用以下代码读取适当的环境变量:

String configFile = System.getProperty(realWarName + ".config.file");
// configFile - "D:\app.properties" for warname.war
// configFile - "D:\app2.properties" for warname2.war