简体   繁体   English

从属性文件访问Maven Pom变量

[英]Accessing Maven Pom Variables From Properties File

I am developing a custom maven plugin. 我正在开发一个自定义maven插件。 When I write: 我写的时候:

${project.version}

into my pom file I can get its value however is there a way if I write into a properties file: 进入我的pom文件我可以得到它的值但是如果我写入属性文件有一种方法:

project.version = ${project.version}

that will set the project.version value correctly, how can I implement it at my Java code? 这将正确设置project.version值,如何在我的Java代码中实现它?

PS: I don't use annotations at my Mojo and I don't want to use variables at my Java code because user should define as my variables as at a properties file and I can not change my core Java code in order to changed things. PS:我没有在我的Mojo上使用注释,我不想在我的Java代码中使用变量,因为用户应该在属性文件中定义我的变量,并且我无法更改我的核心Java代码以便更改内容。

您只需在<build>添加<resources> <build>并打开过滤所需的任何内容即可使用Maven资源过滤

within your mojo if using annotations see http://maven.apache.org/plugin-tools/maven-plugin-plugin/examples/using-annotations.html use 如果使用注释,请在您的mojo中查看http://maven.apache.org/plugin-tools/maven-plugin-plugin/examples/using-annotations.html使用

@Component
protected MavenProject project;

with doclet 与doclet

/**
 * The Maven project to act upon.
 * 
 * @parameter expression="${project}"
 * @required
 */
private MavenProject project;

then project.getVersion() project.getVersion()

You may read and save any property in your pom.xml as i do in this function: 您可以像在此函数中一样读取并保存pom.xml任何属性:

/**
 * Save a property in a pom.xml
 *
 * @param propertyName Name of the property
 * @param value New value for the property
 */
public static void saveProjectProperty(String propertyName, String value)
{
    Model model = null;
    FileReader reader = null;
    MavenXpp3Reader mavenreader = new MavenXpp3Reader();
    try
    {
        reader = new FileReader("pom.xml");
        model = mavenreader.read(reader);
        MavenProject project = new MavenProject(model);
        while (project.getParent() != null)
        {
            project = project.getParent();
        }
        project.getProperties().put(propertyName, value);
        try (FileWriter fileWriter = new FileWriter("pom.xml"))
        {
            project.writeModel(fileWriter);
        }
    }
    catch (IOException ex)
    {
        LOG.severe("Error saving pom.xml");
    }
    catch (XmlPullParserException ex)
    {
        LOG.warning("Error reading pom.xml");
    }
}

To be able to use the clases not native in the JVM you should add these dependencies: 为了能够使用JVM中不是本机的clases,您应该添加这些依赖项:

<dependency>
  <groupId>org.apache.maven</groupId>
  <artifactId>maven-model</artifactId>
  <version>2.0</version>
</dependency>

<dependency>
  <groupId>org.apache.maven</groupId>
  <artifactId>maven-project</artifactId>
  <version>2.0</version>
</dependency

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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