【问题标题】:Is there any way to retrieve the name of the deployed artifact programmatically?有没有办法以编程方式检索已部署工件的名称?
【发布时间】:2015-07-31 21:38:04
【问题描述】:

我正在使用 IntelliJ(和 Maven)构建 Spring Web 服务,并将其部署到 Tomcat 容器中。当我在本地运行它时,它会部署到根应用程序上下文。我想知道是否有一种方法可以以编程方式检索部署在代码中某处的工件的名称。

这就是我在 IntelliJ 中的 Tomcat 配置:

在此示例中,我将服务称为“image-service”,因此它部署了“image-service:war”。 (或者,我可以让它部署“图像服务:战争爆炸”。)我正在寻找一种方法来自动将文字字符串 image-service:war 或至少 image-service 分配给变量。

有什么办法吗?

【问题讨论】:

  • 这些信息是否不在pom.xml 中?
  • 您需要这些信息做什么?
  • 请勿在此处张贴文字图片。浪费您的时间和我们的带宽。

标签: java spring maven tomcat intellij-idea


【解决方案1】:

您需要 Web 应用程序上下文路径。要获取它,请将HttpServletRequest 对象注入您的控制器并使用方法getContextPath() 来检索它。

如果战争部署在根上下文中,您将得到一个空字符串。否则,您将获得部署应用程序的上下文路径(在您的情况下为 /image-service)。


编辑:对评论建议的附加解释:

要使构建时变量(例如工件名称)可用于您的应用程序,您可以使用 maven-war-plugin 将自定义条目放入清单文件中:

<plugin>
 <groupId>org.apache.maven.plugins</groupId>
 <artifactId>maven-war-plugin</artifactId>
 <version>2.2</version>
 <configuration>
     <archive>
         <manifestEntries>
             <distname>${project.build.finalName}</distname>
         </manifestEntries>
     </archive>
 </configuration>
</plugin>

然后,您可以像这样从代码中读取工件名称:

try {
      Properties properties = new Properties();
      properties.load(request.getServletContext()
          .getResourceAsStream("/META-INF/MANIFEST.MF"));
      String distName = properties.getProperty("distname");
 } catch (IOException e) {
    // Handle the exception
 }

【讨论】:

  • 这很好,谢谢。但是如果我要部署到根上下文路径,真的没有其他人可以得到它吗?
  • 嗯...也许在 Maven 构建期间将工件的名称放入清单文件中?然后你可以从你的代码中读取它
猜你喜欢
  • 1970-01-01
  • 2015-02-03
  • 2020-05-13
  • 2023-04-07
  • 1970-01-01
  • 1970-01-01
  • 2010-09-14
  • 2011-01-01
  • 1970-01-01
相关资源
最近更新 更多