如何在生产中测试和运行jar时创建一个可用的MANIFEST.MF?

use*_*216 20 java versioning ant jar manifest.mf

我花了太多时间试图解决这个问题.这应该是最简单的事情,每个在Java中分发Java应用程序的人都必须处理它.

我只是想知道向我的Java应用程序添加版本控制的正确方法,以便我可以在测试时访问版本信息,例如在Eclipse中调试从jar运行.

这是我在build.xml中的内容:

<target name="jar" depends = "compile">
    <property name="version.num" value="1.0.0"/>
    <buildnumber file="build.num"/>
    <tstamp>
        <format property="TODAY" pattern="yyyy-MM-dd HH:mm:ss" />
    </tstamp>

    <manifest file="${build}/META-INF/MANIFEST.MF">
        <attribute name="Built-By" value="${user.name}" />
        <attribute name="Built-Date" value="${TODAY}" />                   
        <attribute name="Implementation-Title" value="MyApp" />
        <attribute name="Implementation-Vendor" value="MyCompany" />                
        <attribute name="Implementation-Version" value="${version.num}-b${build.number}"/>                              
    </manifest>

    <jar destfile="${build}/myapp.jar" basedir="${build}" excludes="*.jar" />                   
</target>
Run Code Online (Sandbox Code Playgroud)

这创建了/META-INF/MANIFEST.MF,我可以在Eclipse中调试时读取值:

public MyClass()
{
    try
    {                        
        InputStream stream = getClass().getResourceAsStream("/META-INF/MANIFEST.MF");
        Manifest manifest = new Manifest(stream);            

        Attributes attributes = manifest.getMainAttributes();

        String implementationTitle = attributes.getValue("Implementation-Title");
        String implementationVersion = attributes.getValue("Implementation-Version");
        String builtDate = attributes.getValue("Built-Date");
        String builtBy = attributes.getValue("Built-By");
   }
   catch (IOException e)
   {            
        logger.error("Couldn't read manifest.");
   }        
Run Code Online (Sandbox Code Playgroud)

}

但是,当我创建jar文件时,它会加载另一个jar的清单(可能是应用程序加载的第一个jar - 在我的例子中,是activation.jar).

此外,尽管所有正确的值都在清单文件中,但以下代码不起作用.

    Package thisPackage = getClass().getPackage();
    String implementationVersion = thisPackage.getImplementationVersion();
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

gib*_*bss 10

您可以在任意jar中获取任意类的清单,而无需解析类URL(可能很脆弱).只需找到您知道的jar所需的资源,然后将连接转换为JarURLConnection.

如果您希望代码在类未捆绑在jar中时工作,请添加一个instanceof检查返回的URL连接类型.解压缩的类层次结构中的类将返回内部Sun FileURLConnection而不是JarUrlConnection.然后,您可以使用其他答案中描述的InputStream方法之一加载Manifest.

@Test
public void testManifest() throws IOException {
    URL res = org.junit.Assert.class.getResource(org.junit.Assert.class.getSimpleName() + ".class");
    JarURLConnection conn = (JarURLConnection) res.openConnection();
    Manifest mf = conn.getManifest();
    Attributes atts = mf.getMainAttributes();
    for (Object v : atts.values()) {
        System.out.println(v);
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 0

只是不要使用清单。创建foo.properties.original文件,内容如version=@VERSION@

在相同的任务中,您可以将副本复制到 copu foo.properties.original,然后