获取jar包版本

  获取maven打包的jar包的版本信息(<groupId>com</groupId><artifactId>jarname</artifactId><version>1.1.0</version>):

    public static String getVersionFromManifest(String jarPath) throws IOException {
        JarFile jar = new JarFile(jarPath);
        Manifest manifest = jar.getManifest();
        Attributes attributes = manifest.getMainAttributes();
        return attributes.getValue(MANIFEST_VERSION_KEY);
    }
  String MANIFEST_VERSION_KEY = "Implementation-Version";

  注意:需要在pom.xml文件的中加入:<addDefaultImplementationEntries>true</addDefaultImplementationEntries>,否则生成的META-INF\MANIFEST.MF文件中不会有Implementation-Version属性

  <build>
    <finalName>jarname</finalName>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.1</version> <!-- 使用当前稳定版本 -->
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
      <!-- 打包为可执行JAR文件 -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
        <version>3.2.0</version> <!-- 使用当前稳定版本 -->
        <!-- 如果需要设置主类以便直接运行JAR -->
        <configuration>
          <!-- 指定MANIFEST.MF中的Main-Class属性 -->
          <archive>
            <manifest>
              <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
              <addClasspath>true</addClasspath>
              <classpathPrefix>lib/</classpathPrefix>
              <mainClass>com.jarname.App</mainClass>
            </manifest>
          </archive>
        </configuration>
      </plugin>

      <!-- 或者使用maven-assembly-plugin创建包含依赖的“fat”或“uber”JAR -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-assembly-plugin</artifactId>
        <version>3.4.2</version>
        <executions>
          <execution>
            <id>make-assembly</id>
            <phase>package</phase> <!-- 绑定到package阶段 -->
            <goals>
              <goal>single</goal>
            </goals>
            <configuration>
              <archive>
                <manifest>
                  <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
                  <mainClass>com.jarname.App</mainClass>
                </manifest>
              </archive>
              <descriptorRefs>
                <descriptorRef>jar-with-dependencies</descriptorRef>
              </descriptorRefs>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>

 

posted @ 2024-01-04 17:10  badwood  阅读(103)  评论(0编辑  收藏  举报
Badwood's Blog