在Maven中生成Version.java文件

在Maven中生成Version.java文件,java,maven-2,code-generation,Java,Maven 2,Code Generation,我有一个使用Ant脚本构建的Java项目。我正在尝试将项目转换为Maven 其中一个任务生成名为Version.Java的Java源文件,该文件包含编译时间戳的静态字符串表示形式,如下所示: package com.foo.bar; public final class Version { public static String VERSION="100301.1046"; } Ant任务非常简单: <target name="version" depends="init" desc

我有一个使用Ant脚本构建的Java项目。我正在尝试将项目转换为Maven

其中一个任务生成名为Version.Java的Java源文件,该文件包含编译时间戳的静态字符串表示形式,如下所示:

package com.foo.bar;
public final class Version {
 public static String VERSION="100301.1046";
}
Ant任务非常简单:

<target name="version" depends="init" description="Create Version.java">
    <echo file="src/${package.dir}/Version.java" message="package ${package.name};${line.separator}" />
    <echo file="src/${package.dir}/Version.java" append="true" message="public final class Version {${line.separator}" />
    <echo file="src/${package.dir}/Version.java"
          append="true"
          message=" public static String VERSION=&quot;${buildtime}&quot;;${line.separator}" />
    <echo file="src/${package.dir}/Version.java" append="true" message="}${line.separator}" />
    <echo message="BUILD ${buildtime}" />
</target>


是否可以在Maven中使用generate sources或其他简单方法执行类似操作?

我认为这不是解决此类问题的好方法

更好的方法是将版本信息放入Java程序将读取的
属性文件中:

您的属性文件将包含以下行:

myapp.version=${project.version}
然后,在您的
pom.xml
中,指出该文件将由Maven保存:

<resources>
    <resource>
        <directory>the/directory/that/contains/your/properties/file</directory>
        <filtering>true</filtering>
    </resource>
</resources>

/directory/包含/your/properties/文件
真的
当Maven构建应用程序时,它将用它们的值替换所有的
${…}
。默认情况下,
${project.version}
定义
pom.xml
的版本(即
标记的值)

然后,在Java代码中,您只需要加载
属性
文件并检索
myApp.version
属性值


请注意,您可以使用设置比当前版本更“复杂”的内容(例如,如果您想在属性中设置构建时间)。

正如@Romain所建议的,您可以从属性文件中读取版本(如果您可以等到打包完成,可以选择
/META-INF/maven/groupId/artifactId/pom.properties
,如果您不能,或者如果它没有提供您所需的一切,可以选择滚动您自己的筛选文件)


你想坚持你的
版本
类,然后看看maven用户列表,它正是针对这个问题提出的解决方案(基于你将在
生成的源代码阶段绑定的antrun插件)。

在更多的谷歌搜索之后,我想到了这个(在pom.xml中):


这是另一个解决方案,将产生与拉尔夫自己的答案相同的结果, 使用pom属性筛选和模板文件:

模板文件(位于src/main/resources/version中的VersionJava.template):

pom:


...
com/foo/bar${project.artifactId}
com.foo.bar${project.artifactId}
版本
${maven.build.timestamp}
src/main/resources/version
VersionJava.template
src/main/resources
版本/*
${ver.template.dir}
*.爪哇
真的
${basedir}/src/main/java/${ver.package.dir}
maven antrun插件
生成源
跑
编译
跑
这似乎有些过分,但它的用途非常广泛,这也是我最喜欢的 我有一个可读格式的模板文件(而不是pom中的echo语句)。 这还允许我修改version类,而不必更改pom,如果您觉得ant有点难看,也可以使用它: pom条目可能是:

<project>
  ...
  <properties>
    <version.template.file>src/main/java/com/stackoverflowVersion.java.template</version.template.file>
<version.file>src/main/java/com/stackoverflow/Version.java</version.file>
  </properties>
  ...
  <build>
    <plugins>
      <plugin>
        <groupId>com.google.code.maven-replacer-plugin</groupId>
            <artifactId>maven-replacer-plugin</artifactId>
            <version>1.4.0</version>
            <executions>                
                <execution>
                    <phase>process-sources</phase>
                    <goals>
                        <goal>replace</goal>
                    </goals>
                </execution>
            </executions>
            <configuration>
                <file>${version.template.file}</file>
                <outputFile>${version.file}</outputFile>
                <replacements>
                    <replacement>
                        <token>@buildnumber@</token>
                        <value>${svn.revision}</value>
                    </replacement>
                    <replacement>
                        <token>@buildtime@</token>
                        <value>${maven.build.timestamp}</value>
                    </replacement>
                    <replacement>
                        <token>@pomversion@</token>
                        <value>${project.version}</value>
                    </replacement>
                </replacements>                        
            </configuration>
      </plugin>
    </plugins>
  </build>
  ...
</project>
package com.stackoverflow;

public final class Version {

    public static final String build_number="@buildnumber@";

    public static final String build_time="@buildtime@";

    public static final String pomversion="@pomversion@";

}

用很少几行XML代码就可以做到这一点的标准方法是现在使用模板化maven插件

请看我的答案

一般来说,Maven的方法是描述你想做什么。然后如何。当how需要数十行或数百行XML时,要么找到正确的插件,要么编写它。这就是创建模板Maven插件的基本原理:-)。

基于。这是一个简化版本,无需设置额外属性。仅将项目的版本复制到version.java中

Version.java
放入
src/main/templates

package thepackage;

public final class Version {

 public static String VERSION="${project.version}";

}
指示maven替换Version.java中的令牌

<resources>
    <resource>
        <directory>src/main/templates</directory>
        <includes>
            <include>*.java</include>
        </includes>
        <filtering>true</filtering>
        <targetPath>${project.build.directory}/generated-sources/java/thepackage</targetPath>
    </resource>
</resources>
最后,让我们来看一下eclipsem2e

  • 注意新的构建路径
  • 不要陷入无休止的循环建设
第二点是通过在eclipse的增量构建期间禁用

<pluginManagement>
    <plugins>
        <plugin>
            <groupId>org.eclipse.m2e</groupId>
            <artifactId>lifecycle-mapping</artifactId>
            <version>1.0.0</version>
            <configuration>
                <lifecycleMappingMetadata>
                    <pluginExecutions>
                        <pluginExecution>
                          <pluginExecutionFilter>
                            <groupId>org.codehaus.mojo</groupId>
                            <artifactId>build-helper-maven-plugin</artifactId>
                            <versionRange>[1.0,)</versionRange>
                            <goals>
                              <goal>parse-version</goal>
                              <goal>add-source</goal>
                              <goal>maven-version</goal>
                              <goal>add-resource</goal>
                              <goal>add-test-resource</goal>
                              <goal>add-test-source</goal>
                            </goals>
                          </pluginExecutionFilter>
                          <action>
                            <execute>
                              <runOnConfiguration>true</runOnConfiguration>
                              <runOnIncremental>true</runOnIncremental>
                            </execute>
                          </action>
                        </pluginExecution>
                        <pluginExecution>
                            <pluginExecutionFilter>
                                <groupId>org.apache.maven.plugins</groupId>
                                <artifactId>maven-resources-plugin</artifactId>
                                <versionRange>[1.0.0,)</versionRange>
                                <goals>
                                    <goal>resources</goal>
                                </goals>
                            </pluginExecutionFilter>
                            <action>
                                <execute>
                                    <runOnConfiguration>true</runOnConfiguration>
                                    <runOnIncremental>false</runOnIncremental>
                                </execute>
                            </action>
                        </pluginExecution>
                    </pluginExecutions>
                </lifecycleMappingMetadata>
            </configuration>
        </plugin>
    </plugins>
</pluginManagement>

org.eclipse.m2e
生命周期映射
1.0.0
org.codehaus.mojo
构建助手maven插件
[1.0,)
解析版本
添加源
maven版本
添加资源
添加测试资源
添加测试源
真的
真的
org.apache.maven.plugins
maven资源插件
[1.0.0,)
资源
package thepackage;

public final class Version {

 public static String VERSION="${project.version}";

}
<resources>
    <resource>
        <directory>src/main/templates</directory>
        <includes>
            <include>*.java</include>
        </includes>
        <filtering>true</filtering>
        <targetPath>${project.build.directory}/generated-sources/java/thepackage</targetPath>
    </resource>
</resources>
<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>build-helper-maven-plugin</artifactId>
    <version>1.8</version>
    <executions>
        <execution>
             <id>add-source</id>
            <phase>generate-sources</phase>
            <goals>
                <goal>add-source</goal>
            </goals>
            <configuration>
                <sources>
                    <source>${project.build.directory}/generated-sources/java/</source>
                </sources>
            </configuration>
        </execution>
    </executions>
</plugin>
<pluginManagement>
    <plugins>
        <plugin>
            <groupId>org.eclipse.m2e</groupId>
            <artifactId>lifecycle-mapping</artifactId>
            <version>1.0.0</version>
            <configuration>
                <lifecycleMappingMetadata>
                    <pluginExecutions>
                        <pluginExecution>
                          <pluginExecutionFilter>
                            <groupId>org.codehaus.mojo</groupId>
                            <artifactId>build-helper-maven-plugin</artifactId>
                            <versionRange>[1.0,)</versionRange>
                            <goals>
                              <goal>parse-version</goal>
                              <goal>add-source</goal>
                              <goal>maven-version</goal>
                              <goal>add-resource</goal>
                              <goal>add-test-resource</goal>
                              <goal>add-test-source</goal>
                            </goals>
                          </pluginExecutionFilter>
                          <action>
                            <execute>
                              <runOnConfiguration>true</runOnConfiguration>
                              <runOnIncremental>true</runOnIncremental>
                            </execute>
                          </action>
                        </pluginExecution>
                        <pluginExecution>
                            <pluginExecutionFilter>
                                <groupId>org.apache.maven.plugins</groupId>
                                <artifactId>maven-resources-plugin</artifactId>
                                <versionRange>[1.0.0,)</versionRange>
                                <goals>
                                    <goal>resources</goal>
                                </goals>
                            </pluginExecutionFilter>
                            <action>
                                <execute>
                                    <runOnConfiguration>true</runOnConfiguration>
                                    <runOnIncremental>false</runOnIncremental>
                                </execute>
                            </action>
                        </pluginExecution>
                    </pluginExecutions>
                </lifecycleMappingMetadata>
            </configuration>
        </plugin>
    </plugins>
</pluginManagement>
     <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-war-plugin</artifactId>
        <version>2.6</version>
        <configuration>
           <archive>
              <manifest>
                 <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
                 <addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
              </manifest>
              <manifestEntries>
                 <Build-Time>${maven.build.timestamp}</Build-Time>
              </manifestEntries>
           </archive>
        </configuration>
     </plugin>
Manifest-Version: 1.0
Implementation-Title: MyApp
Implementation-Version: 2.11.0-SNAPSHOT
Built-By: niestroj
Specification-Title: MyApp
Implementation-Vendor-Id: com.mycompany
Build-Time: 2017-01-09 15:30
Created-By: Apache Maven 3.0.5
Build-Jdk: 1.8.0_40
Specification-Version: 2.11
  try {
     Manifest manifest = new Manifest(getServletContext().getResourceAsStream("/META-INF/MANIFEST.MF"));
     Attributes attributes = manifest.getMainAttributes();
     attributes.getValue("Implementation-Version");
     attributes.getValue("Build-Time");
  } catch (IOException ex) {
     LOGGER.debug("Error reading manifest file information", ex);
  }
package com.foo.bar;
public final class Version {
    public static final String VERSION = "${project.version}";
}