如何记录pom工件和版本 [英] How to log the pom artifact and version

查看:33
本文介绍了如何记录pom工件和版本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Projecta中,我在ClassA中有一个MethodA,Projecta JAR作为Maven依赖添加到不同的项目中,不同的项目都在调用MethodA

要求为

每当ClassAMethodA被任何其他项目调用时,考虑到这些项目pom.xml中添加了ProjectA依赖项,我们需要记录调用的项目工件ID和版本。

备注

下面仅适用于自我项目(ProjectA)、属性文件创建和打开maven资源筛选

 Create a property file

 src/main/resources/project.properties
 with the below content

version=${project.version}
artifactId=${project.artifactId}
Now turn on maven resource filtering

<resource>
 <directory>src/main/resources</directory>
 <filtering>true</filtering>
</resource>

方法A

public class ClassA {
    final static Logger logger = Logger.getLogger(ClassA.class);

    public void MethodA{
        final Properties properties = new Properties();
        properties.load(this.getClassLoader().getResourceAsStream("project.properties"));
        logger.info(properties.getProperty("version"));
        logger.info(properties.getProperty("artifactId"));
          } 
}

在项目B中调用MethodA时,我在记录器中得到以下输出

   version=${project.version}
   artifactId=${project.artifactId}    which is incorrect.

预期输出:

version = 1.0.0
artifactId = ProjectB

有没有更好的方法来记录调用项目工件ID?如果MethodA由ProjectC调用,我们希望获取ProjectC项目ID和版本。

要求:我们有30多个项目从Projecta调用MethodA,因此不应对调用项目进行任何更改。

推荐答案

解决方案A:Maven资源筛选

如果您将POM代码段放在正确的POM部分,则它应该正确替换变量:

<build>
  <resources>
    <resource>
      <directory>src/main/resources</directory>
      <filtering>true</filtering>
    </resource>
  </resources>
</build>
您可以在target/classes文件夹中检查结果。在我通过将空参数列表()添加到方法名并将无意义的this.getClassLoader()替换为getClass().getClassLoader()来修复错误的伪代码之后,代码甚至编译并做了一些有意义的事情。在将内容发布到StackOverflow这样的公共平台之前,您是否进行过测试?

import java.io.IOException;
import java.util.Properties;

public class ClassA {
  public void methodA() throws IOException {
    final Properties properties = new Properties();
    properties.load(getClass().getClassLoader().getResourceAsStream("project.properties"));
    System.out.println(properties.getProperty("version"));
    System.out.println(properties.getProperty("artifactId"));
  }

  public static void main(String[] args) throws IOException {
    new ClassA().methodA();
  }
}

mvn compile之后从IntelliJ IDEA运行时的控制台日志(因为我们需要Maven处理资源并将其复制到target/classes):

1.9.8-SNAPSHOT
util

或您的模块名称和版本。

如果您看到的是变量名,则可能是您的类路径没有指向JAR,而是以某种方式指向了源目录,或者您有多个具有project.properties文件的模块,并且其中一个模块忘记了资源过滤。无论在类路径上最先找到哪个文件,都将加载。所以在一个多模块的项目中,最好使用不同的文件名,否则先找到哪一个或多或少都是抽签。

下一个问题将是您的方面或其他模块知道要加载哪个资源文件,以便最好以某种方式链接到类或包名,以便其他模块能够从包名猜测资源文件。那么,您确实需要清楚地将模块之间的包名隔开。我真想知道这么麻烦是否值得。

解决方案B:模板化Maven插件+package-info.java+自定义批注

另一个想法是使用资源过滤或像org.codehaus.mojo:templating-maven-plugin这样的插件将版本直接替换到package annotation values in a package-info.java file中,然后在运行时简单地从包信息中获取这些值。我用那个插件做了一个快速和肮脏的本地测试,它工作得很好。我建议现在保持简单,只修复您的资源过滤问题。如果您需要我刚才描述的更通用的解决方案,请告诉我。

项目结构

更新:我将侵入其中一个项目的快速解决方案解压到一个新的Maven多模块项目中,以便向您展示一个干净的解决方案,如下所示:

假设我们有一个带有3个子模块的父POM:

  • annotation-包含要在package-info.java文件中的包上使用的注释。可以轻松修改为也适用于类。
  • library-应用程序模块要访问的示例库
  • application-示例应用

您可以在GitHub上找到完整的项目: https://github.com/kriegaex/SO_Maven_ArtifactInfoRuntime_68321439

工程目录布局如下:

$ tree
.
├── annotation
│   ├── pom.xml
│   └── src
│       └── main
│           └── java
│               └── de
│                   └── scrum_master
│                       └── stackoverflow
│                           └── q68321439
│                               └── annotation
│                                   └── MavenModuleInfo.java
├── application
│   ├── pom.xml
│   └── src
│       ├── main
│       │   ├── java
│       │   │   └── de
│       │   │       └── scrum_master
│       │   │           └── stackoverflow
│       │   │               └── q68321439
│       │   │                   └── application
│       │   │                       └── Application.java
│       │   └── java-templates
│       │       └── de
│       │           └── scrum_master
│       │               └── stackoverflow
│       │                   └── q68321439
│       │                       └── application
│       │                           └── package-info.java
│       └── test
│           └── java
│               └── de
│                   └── scrum_master
│                       └── stackoverflow
│                           └── q68321439
│                               └── application
│                                   └── ModuleInfoTest.java
├── library
│   ├── pom.xml
│   └── src
│       └── main
│           ├── java
│           │   └── de
│           │       └── scrum_master
│           │           └── stackoverflow
│           │               └── q68321439
│           │                   └── library
│           │                       └── LibraryClass.java
│           └── java-templates
│               └── de
│                   └── scrum_master
│                       └── stackoverflow
│                           └── q68321439
│                               └── library
│                                   └── package-info.java
└── pom.xml
请注意库和应用程序模块中的src/java-templates目录,其中包含package-info.java个文件。目录名称是Templating Maven Plugin的默认名称,使插件配置不那么繁琐。

父POM

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>de.scrum-master.stackoverflow.q68321439</groupId>
  <artifactId>maven-artifact-info-runtime</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>pom</packaging>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <maven.compiler.source>8</maven.compiler.source>
    <maven.compiler.target>8</maven.compiler.target>
  </properties>

  <modules>
    <module>annotation</module>
    <module>library</module>
    <module>application</module>
  </modules>

  <build>
    <pluginManagement>
      <plugins>
        <plugin>
          <groupId>org.codehaus.mojo</groupId>
          <artifactId>templating-maven-plugin</artifactId>
          <version>1.0.0</version>
          <executions>
            <execution>
              <id>filter-src</id>
              <goals>
                <goal>filter-sources</goal>
              </goals>
            </execution>
          </executions>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>

</project>

模块annotation

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>de.scrum-master.stackoverflow.q68321439</groupId>
    <artifactId>maven-artifact-info-runtime</artifactId>
    <version>1.0-SNAPSHOT</version>
  </parent>

  <artifactId>annotation</artifactId>

</project>
package de.scrum_master.stackoverflow.q68321439.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PACKAGE)
public @interface MavenModuleInfo {
  String groupId();
  String artifactId();
  String version();
}

模块library

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>de.scrum-master.stackoverflow.q68321439</groupId>
    <artifactId>maven-artifact-info-runtime</artifactId>
    <version>1.0-SNAPSHOT</version>
  </parent>

  <artifactId>library</artifactId>

  <build>
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>templating-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>

  <dependencies>
    <dependency>
      <groupId>de.scrum-master.stackoverflow.q68321439</groupId>
      <artifactId>annotation</artifactId>
      <version>${project.version}</version>
    </dependency>
  </dependencies>

</project>
package de.scrum_master.stackoverflow.q68321439.library;

public class LibraryClass {}
请注意,以下文件需要位于library/src/main/java-templates/de/scrum_master/stackoverflow/q68321439/library/package-info.java中。在这里,您可以看到我们如何通过模板化Maven插件,在构建过程中使用Maven属性被它们的相应值替换:

/**
 * This is the package description (...)
 */
@MavenModuleInfo(groupId = "${project.groupId}", artifactId = "${project.artifactId}", version = "${project.version}")
package de.scrum_master.stackoverflow.q68321439.library;

import de.scrum_master.stackoverflow.q68321439.annotation.MavenModuleInfo;

模块application

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>de.scrum-master.stackoverflow.q68321439</groupId>
    <artifactId>maven-artifact-info-runtime</artifactId>
    <version>1.0-SNAPSHOT</version>
  </parent>

  <artifactId>application</artifactId>

  <build>
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>templating-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>

  <dependencies>
    <dependency>
      <groupId>de.scrum-master.stackoverflow.q68321439</groupId>
      <artifactId>annotation</artifactId>
      <version>${project.version}</version>
    </dependency>
    <dependency>
      <groupId>de.scrum-master.stackoverflow.q68321439</groupId>
      <artifactId>library</artifactId>
      <version>${project.version}</version>
    </dependency>
    <dependency>
      <groupId>de.scrum-master.stackoverflow.q68321439</groupId>
      <artifactId>library</artifactId>
      <version>${project.version}</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.13.2</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

</project>
package de.scrum_master.stackoverflow.q68321439.application;

public class Application {
  public static void main(String[] args) {}
}
请注意,以下文件需要位于application/src/main/java-templates/de/scrum_master/stackoverflow/q68321439/application/package-info.java中。在这里,您可以看到我们如何通过模板化Maven插件,在构建过程中使用Maven属性被它们的相应值替换:

/**
 * This is the package description (...)
 */
@MavenModuleInfo(groupId = "${project.groupId}", artifactId = "${project.artifactId}", version = "${project.version}")
package de.scrum_master.stackoverflow.q68321439.application;

import de.scrum_master.stackoverflow.q68321439.annotation.MavenModuleInfo;
package de.scrum_master.stackoverflow.q68321439.application;

import de.scrum_master.stackoverflow.q68321439.annotation.MavenModuleInfo;
import de.scrum_master.stackoverflow.q68321439.library.LibraryClass;
import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class ModuleInfoTest {
  @Test
  public void test() {
    String groupId = "de.scrum-master.stackoverflow.q68321439";

    MavenModuleInfo libMavenInfo = logAndGetMavenModuleInfo("Library Maven info", LibraryClass.class.getPackage());
    assertEquals(groupId, libMavenInfo.groupId());
    assertEquals("library", libMavenInfo.artifactId());

    MavenModuleInfo appMavenInfo = logAndGetMavenModuleInfo("Application Maven info", Application.class.getPackage());
    assertEquals(groupId, appMavenInfo.groupId());
    assertEquals("application", appMavenInfo.artifactId());
  }

  private MavenModuleInfo logAndGetMavenModuleInfo(String message, Package aPackage) {
    MavenModuleInfo moduleInfo = aPackage.getAnnotation(MavenModuleInfo.class);
    System.out.println(message);
    System.out.println("  " + moduleInfo.groupId());
    System.out.println("  " + moduleInfo.artifactId());
    System.out.println("  " + moduleInfo.version());
    return moduleInfo;
  }
}

运行Maven内部版本

现在通过mvn clean test运行Maven构建:

(...)
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ application ---
[INFO] Surefire report directory: C:UsersalexaDocumentsjava-srcSO_Maven_ArtifactInfoRuntime_68321439application	argetsurefire-reports

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running de.scrum_master.stackoverflow.q68321439.application.ModuleInfoTest
Library Maven info
  de.scrum-master.stackoverflow.q68321439
  library
  1.0-SNAPSHOT
Application Maven info
  de.scrum-master.stackoverflow.q68321439
  application
  1.0-SNAPSHOT
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.094 sec
(...)

标识调用者

假设所有调用模块使用包信息+特殊注释实现相同的方案,则可以这样打印调用者信息:

package de.scrum_master.stackoverflow.q68321439.library;

import de.scrum_master.stackoverflow.q68321439.annotation.MavenModuleInfo;

public class LibraryClass {
  public void doSomething() {
    StackTraceElement callerStackTraceElement = new Exception().getStackTrace()[1];
    try {
      Class<?> callerClass = Class.forName(callerStackTraceElement.getClassName());
      MavenModuleInfo mavenModuleInfo = callerClass.getPackage().getAnnotation(MavenModuleInfo.class);
      System.out.println(mavenModuleInfo.groupId());
      System.out.println(mavenModuleInfo.artifactId());
      System.out.println(mavenModuleInfo.version());
    }
    catch (ClassNotFoundException e) {
      e.printStackTrace();
    }
  }

  public void doSomethingJava9() {
    Class<?> callerClass = StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE).getCallerClass();
    MavenModuleInfo mavenModuleInfo = callerClass.getPackage().getAnnotation(MavenModuleInfo.class);
    System.out.println(mavenModuleInfo.groupId());
    System.out.println(mavenModuleInfo.artifactId());
    System.out.println(mavenModuleInfo.version());
  }

}
虽然doSomething()也适用于旧Java版本(在Java8上测试),但在Java9+上可以使用JEP 259 Stack-Walking API,如doSomethingJava9()所示。在这种情况下,您不需要手动解析异常堆栈跟踪和处理异常。

解决方案C:通过URL类加载器标识调用JAR

假设您使用我的示例项目并从应用程序模块调用库(如上一节所示),打印JAR信息的一种快捷方式是:

将此方法添加到LibraryClass

  public void doSomethingClassLoader() {
    StackTraceElement callerStackTraceElement = new Exception().getStackTrace()[1];
    try {
      Class<?> callerClass = Class.forName(callerStackTraceElement.getClassName());
      // Cheap way of getting Maven artifact name - TODO: parse
      System.out.println(
        callerClass
          .getClassLoader()
          .getResource(callerStackTraceElement.getClassName().replaceAll("[.]", "/") + ".class")
      );
    }
    catch (ClassNotFoundException e) {
      e.printStackTrace();
    }
  }

同样,在Java9+上,您可以通过使用Stack-Walking API使代码更好,请参见上文。

Application调用方法:

public class Application {
  public static void main(String[] args) {
//    new LibraryClass().doSomething();
//    new LibraryClass().doSomethingJava9();
    new LibraryClass().doSomethingClassLoader();
  }
}

现在从命令行构建Maven应用程序,并使用3个不同的类路径运行,指向

  1. target/classes目录
  2. target目录中的JAR
  3. 本地Maven存储库中的JAR 要查看将哪些信息打印到控制台:
$ mvn install
(...)

$ java -cp "annotation	argetannotation-1.0-SNAPSHOT.jar;library	argetlibrary-1.0-SNAPSHOT.jar;application	argetclasses" de.scrum_master.stackoverflow.q68321439.application.Application

file:/C:/Users/alexa/Documents/java-src/SO_Maven_ArtifactInfoRuntime_68321439/application/target/classes/de/scrum_master/stackoverflow/q68321439/application/Application.class

$ java -cp "annotation	argetannotation-1.0-SNAPSHOT.jar;library	argetlibrary-1.0-SNAPSHOT.jar;application	argetapplication-1.0-SNAPSHOT.jar" de.scrum_master.stackoverflow.q68321439.application.Application

jar:file:/C:/Users/alexa/Documents/java-src/SO_Maven_ArtifactInfoRuntime_68321439/application/target/application-1.0-SNAPSHOT.jar!/de/scrum_master/stackoverflow/q68321439/application/Application.class

$ java -cp "annotation	argetannotation-1.0-SNAPSHOT.jar;library	argetlibrary-1.0-SNAPSHOT.jar;c:UsersAlexa.m2
epositorydescrum-masterstackoverflowq68321439application1.0-SNAPSHOTapplication-1.0-SNAPSHOT.jar" de.scrum_master.stackoverflow.q68321439.application.Application

jar:file:/C:/Users/alexa/.m2/repository/de/scrum-master/stackoverflow/q68321439/application/1.0-SNAPSHOT/application-1.0-SNAPSHOT.jar!/de/scrum_master/stackoverflow/q68321439/application/Application.class

如您所见

  • 在第一种情况下,您可以从项目路径间接推断Maven工件
  • 在案例2中,您可以在JAR名称中看到工件ID和版本,在项目路径中间接看到组ID
  • 在案例3中,您可以直接在Maven存储库路径中看到JAR名称中的工件ID和版本,以及Maven存储库路径中的组ID。

当然,您可以解析该信息并以更结构化的方式打印它,但我建议您只需像这样打印它,然后让阅读日志的人脑执行解析。

就像我在前面的评论中所说的,这在我向您展示的案例中工作得很好,也适用于不同的项目,而不仅仅是单个多模块项目。在应用程序服务器部署或超级JAR情况下,您将看到什么类型的信息,这在很大程度上取决于确切的情况。没有单一的、通用的答案,我也不能为你做全部的工作。我向您展示了几个选项,现在您可以选择一个。

这篇关于如何记录pom工件和版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆