简体   繁体   中英

Is there any way to retrieve the name of the deployed artifact programmatically?

I'm building a Spring web service, using IntelliJ (and Maven), and deploying it into a Tomcat container. When I run it locally, it deploys to the root application context. I'm wondering if there's a way that I can programmatically retrieve the name of the artifact deployed somewhere in code.

So here's what my Tomcat configuration looks like in IntelliJ:

在此处输入图片说明

In this example I called the service "image-service" and so it deploys "image-service:war". (Alternatively, I could have it deploy "image-service:war exploded".) I'm looking for a way to assign to a variable the literal string image-service:war , or at the very least image-service , automatically.

Is there any way to do this?

You need the web application context path. To get it, inject the HttpServletRequest object into your controller and use method getContextPath() to retrieve it.

If the war is deployed in the root context you will get an empty string. Otherwise, you will get the context path under which the application is deployed (in your case /image-service ).


Edit: Additional explanation for the suggestion from comment:

To make build-time variables (eg artifact name) available to your application, you can put custom entries in the manifest file using 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>

Then, you can read the artifact name from your code like this:

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
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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