如何在多个Maven项目之间共享公共属性?

55

我有几个通过Maven构建的项目,我想在它们之间共享一些常见属性——Spring版本、MySQL驱动程序版本、svn基本URL等,这样我可以一次更新所有项目并反映到所有项目上。

我考虑使用一个超级POM来存储所有的属性,但如果我更改了其中一个属性,我需要逐个增加其版本(并更新从中继承的所有POM),或者删除所有开发人员机器上的POM(这是不想做的)。

能够将这些参数指定为POM外部吗?我仍想在父POM中定义外部位置。


1
走超级pom路线,每当您更新超级pom版本号时,执行:mvn -N versions:update-child-modules https://dev59.com/pHVD5IYBdhLWcg3wR5go - Tim
@Tim 的问题是我有一个层次结构,包括几个超级 POM(通用定义 -> Spring 项目 -> Web 应用程序/服务 -> 实际模块)。据我所知,版本插件无法进行级联更新。 - David Rabinowitz
3个回答

29
你可以使用Properties Maven插件,将属性定义在外部文件中,让插件读取文件。用以下配置:
<build>
    <plugins>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>properties-maven-plugin</artifactId>
            <version>1.0-alpha-1</version>
            <executions>
                <execution>
                    <phase>initialize</phase>
                    <goals>
                        <goal>read-project-properties</goal>
                    </goals>
                    <configuration>
                        <files>
                            <file>my-file.properties</file>
                        </files>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

如果你在你的属性文件中有以下行:

spring-version=1.0
mysql-version=4.0.0

那么这与在pom.xml文件中编写以下行相同:

<properties>
    <spring-version>1.0</spring-version>
    <mysql-version>4.0.0</mysql-version>
</properties>

使用这个插件,您将获得以下几个好处:

  • 轻松设置大量属性
  • 修改这些属性的值而不修改父级 pom.xml 文件。

考虑到这是 alpha-1 版本,这个插件有多成熟? - David Rabinowitz
1
根据这个 bug,对我来说它仍然无法使用,因为我想在父 POM 中有减速功能:http://jira.codehaus.org/browse/MOJO-1303 - David Rabinowitz
你能提供一个完整的 pom.com 文件,其中引用了 spring-version 吗?根据 https://dev59.com/anRA5IYBdhLWcg3wuAcp 中的讨论,定义依赖项的版本是不可能的,对吗? - dma_k
3
这个回答是不正确的,因为依赖图创建时机和读取属性时机不同于您编写版本属性并将其传递给依赖项,这是由于它们发生的顺序。如果您打算使用这些属性声明依赖项的版本,则从文件中读取这些属性实际上是无用的。请注意,创建依赖图的操作先于读取属性的操作。 - niken
你打算把这个properties文件存放在哪里?如果它被Git仓库A和B中的两个不同项目共用,该怎么办? - Kashyap
当我在</build>结束标签之后,在常规的Maven插件之前,在<plugins>下输入此<plugin>部分时,我遇到了以下错误:插件“execution”未被生命周期配置所覆盖:org.codehaus.mojo:properties-maven-plugin:1.0-alpha-1:read-project-properties(execution: default,phase: initialize)如何纠正它? - PraNuta

14
请注意,这里的原始想法是我正在做的事情,但我可能已经找到了一个更好的想法,我也在下面列出了。 我想保留这两个想法以便完整性考虑,以防新想法不起作用


我认为您可以使用parent pom来解决此问题,但需要具备Maven仓库和CI构建工具。

我有几个项目,所有这些项目都从父POM继承基本属性。 我们使用Java 1.5,因此该构建属性在那里设置。 一切都是UTF-8。 我希望运行的所有报告,Sonar设置等都在父POM中。

假设您的项目已经在版本控制中,并且您有一个CI工具,在您检入时,CI工具可以构建POM项目并将SNAPSHOT部署到maven repos。 如果您的项目指向父POM的SNAPSHOT版本,则它们将检查存储库以验证它们是否拥有最新版本...如果没有,它们将下载最新版本。 因此,如果更新父代,所有其他项目都将更新。

我想关键是发布SNAPSHOT。 我会说,您的发布次数要比更改次数少得多。 所以您可以释放POM,然后更新从中继承的POM并将其检入版本控制。 让开发人员知道他们需要进行更新,然后继续操作。

您可以触发构建以强制新POM进入存储库,然后让所有开发人员在构建时自动获取更改。


我已删除了关键字LATEST/RELEASE的想法,因为它们不适用于父POM。 它们仅适用于依赖项或插件。 问题出在DefaultMavenProjectBuilder上。 实质上,它难以确定要查找父级的存储库以确定最新或发布版本是哪个。 虽然不知道为什么对于依赖项或插件会有所不同。


看起来这些方法比每次更改父POM都要少痛苦。


如果项目已经存在一个父POM,如何添加该父POM? - inetphantom

7
我认为properties-maven-plugin是长期以来正确的方法,但正如你回答该答案所述,它不允许属性被继承。在maven-shared-io中有一些工具可以让您在项目类路径上发现资源。下面的代码扩展了属性插件,以查找插件依赖项中的属性文件。
配置声明了一个指向属性文件的路径,因为描述符项目在插件配置中声明,所以它可以被ClasspathResourceLocatorStrategy访问。该配置可以在父项目中定义,并将被所有子项目继承(如果这样做,请避免声明任何文件,因为它们不会被发现,只设置filePaths属性)。
以下配置假定有另一个名为name.seller.rich:test-properties-descriptor:0.0.1的jar项目,其中包含一个名为external.properties的文件(即它在src/main/resources中定义)。
<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>properties-ext-maven-plugin</artifactId>
  <version>0.0.1</version>
  <executions>
    <execution>
      <id>read-properties</id>
      <phase>initialize</phase>
      <goals>
        <goal>read-project-properties</goal>
      </goals>
    </execution>
  </executions>                              
  <configuration>
    <filePaths>
      <filePath>external.properties</filePath>
    </filePaths>
  </configuration> 
  <dependencies>
    <!-- declare any jars that host the required properties files here -->
    <dependency>
      <groupId>name.seller.rich</groupId>
      <artifactId>test-properties-descriptor</artifactId>
      <version>0.0.1</version>
    </dependency>
  </dependencies>
</plugin>

该插件项目的POM文件如下所示:
<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>properties-ext-maven-plugin</artifactId>
  <packaging>maven-plugin</packaging>
  <version>0.0.1</version>
  <dependencies>
    <dependency>
      <groupId>org.codehaus.mojo</groupId>
      <artifactId>properties-maven-plugin</artifactId>
      <version>1.0-alpha-1</version>
    </dependency>
    <dependency>
      <groupId>org.apache.maven.shared</groupId>
      <artifactId>maven-shared-io</artifactId>
      <version>1.1</version>
    </dependency>
  </dependencies>
</project>

Mojo是属性插件ReadPropertiesMojo的一个副本,它增加了一个“filePaths”属性,允许您定义类路径中外部属性文件的相对路径,这使得文件属性变为可选,并添加了readPropertyFiles()和getLocation()方法来定位文件并将任何filePath合并到文件数组中,然后继续执行。我已经评论了我的更改,以使它们更清晰。

package org.codehaus.mojo.xml;

/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file 
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, 
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 
 * KIND, either express or implied.  See the License for the 
 * specific language governing permissions and limitations 
 * under the License.
 */

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.project.MavenProject;
import org.apache.maven.shared.io.location.ClasspathResourceLocatorStrategy;
import org.apache.maven.shared.io.location.FileLocatorStrategy;
import org.apache.maven.shared.io.location.Location;
import org.apache.maven.shared.io.location.Locator;
import org.apache.maven.shared.io.location.LocatorStrategy;
import org.apache.maven.shared.io.location.URLLocatorStrategy;
import org.codehaus.plexus.util.cli.CommandLineUtils;

/**
 * The read-project-properties goal reads property files and stores the
 * properties as project properties. It serves as an alternate to specifying
 * properties in pom.xml.
 * 
 * @author <a href="mailto:zarars@gmail.com">Zarar Siddiqi</a>
 * @author <a href="mailto:Krystian.Nowak@gmail.com">Krystian Nowak</a>
 * @version $Id: ReadPropertiesMojo.java 8861 2009-01-21 15:35:38Z pgier $
 * @goal read-project-properties
 */
public class ReadPropertiesMojo extends AbstractMojo {
    /**
     * @parameter default-value="${project}"
     * @required
     * @readonly
     */
    private MavenProject project;

    /**
     * The properties files that will be used when reading properties.
     * RS: made optional to avoid issue for inherited plugins
     * @parameter
     */
    private File[] files;

    //Begin: RS addition
    /**
     * Optional paths to properties files to be used.
     * 
     * @parameter
     */
    private String[] filePaths;
    //End: RS addition

    /**
     * If the plugin should be quiet if any of the files was not found
     * 
     * @parameter default-value="false"
     */
    private boolean quiet;

    public void execute() throws MojoExecutionException {
        //Begin: RS addition
        readPropertyFiles();
        //End: RS addition

        Properties projectProperties = new Properties();
        for (int i = 0; i < files.length; i++) {
            File file = files[i];

            if (file.exists()) {
                try {
                    getLog().debug("Loading property file: " + file);

                    FileInputStream stream = new FileInputStream(file);
                    projectProperties = project.getProperties();

                    try {
                        projectProperties.load(stream);
                    } finally {
                        if (stream != null) {
                            stream.close();
                        }
                    }
                } catch (IOException e) {
                    throw new MojoExecutionException(
                            "Error reading properties file "
                                    + file.getAbsolutePath(), e);
                }
            } else {
                if (quiet) {
                    getLog().warn(
                            "Ignoring missing properties file: "
                                    + file.getAbsolutePath());
                } else {
                    throw new MojoExecutionException(
                            "Properties file not found: "
                                    + file.getAbsolutePath());
                }
            }
        }

        boolean useEnvVariables = false;
        for (Enumeration n = projectProperties.propertyNames(); n
                .hasMoreElements();) {
            String k = (String) n.nextElement();
            String p = (String) projectProperties.get(k);
            if (p.indexOf("${env.") != -1) {
                useEnvVariables = true;
                break;
            }
        }
        Properties environment = null;
        if (useEnvVariables) {
            try {
                environment = CommandLineUtils.getSystemEnvVars();
            } catch (IOException e) {
                throw new MojoExecutionException(
                        "Error getting system envorinment variables: ", e);
            }
        }
        for (Enumeration n = projectProperties.propertyNames(); n
                .hasMoreElements();) {
            String k = (String) n.nextElement();
            projectProperties.setProperty(k, getPropertyValue(k,
                    projectProperties, environment));
        }
    }

    //Begin: RS addition
    /**
     * Obtain the file from the local project or the classpath
     * 
     * @throws MojoExecutionException
     */
    private void readPropertyFiles() throws MojoExecutionException {
        if (filePaths != null && filePaths.length > 0) {
            File[] allFiles;

            int offset = 0;
            if (files != null && files.length != 0) {
                allFiles = new File[files.length + filePaths.length];
                System.arraycopy(files, 0, allFiles, 0, files.length);
                offset = files.length;
            } else {
                allFiles = new File[filePaths.length];
            }

            for (int i = 0; i < filePaths.length; i++) {
                Location location = getLocation(filePaths[i], project);

                try {
                    allFiles[offset + i] = location.getFile();
                } catch (IOException e) {
                    throw new MojoExecutionException(
                            "unable to open properties file", e);
                }
            }

            // replace the original array with the merged results
            files = allFiles;
        } else if (files == null || files.length == 0) {
            throw new MojoExecutionException(
                    "no files or filePaths defined, one or both must be specified");
        }
    }
    //End: RS addition

    /**
     * Retrieves a property value, replacing values like ${token} using the
     * Properties to look them up. Shamelessly adapted from:
     * http://maven.apache.
     * org/plugins/maven-war-plugin/xref/org/apache/maven/plugin
     * /war/PropertyUtils.html
     * 
     * It will leave unresolved properties alone, trying for System properties,
     * and environment variables and implements reparsing (in the case that the
     * value of a property contains a key), and will not loop endlessly on a
     * pair like test = ${test}
     * 
     * @param k
     *            property key
     * @param p
     *            project properties
     * @param environment
     *            environment variables
     * @return resolved property value
     */
    private String getPropertyValue(String k, Properties p,
            Properties environment) {
        String v = p.getProperty(k);
        String ret = "";
        int idx, idx2;

        while ((idx = v.indexOf("${")) >= 0) {
            // append prefix to result
            ret += v.substring(0, idx);

            // strip prefix from original
            v = v.substring(idx + 2);

            idx2 = v.indexOf("}");

            // if no matching } then bail
            if (idx2 < 0) {
                break;
            }

            // strip out the key and resolve it
            // resolve the key/value for the ${statement}
            String nk = v.substring(0, idx2);
            v = v.substring(idx2 + 1);
            String nv = p.getProperty(nk);

            // try global environment
            if (nv == null) {
                nv = System.getProperty(nk);
            }

            // try environment variable
            if (nv == null && nk.startsWith("env.") && environment != null) {
                nv = environment.getProperty(nk.substring(4));
            }

            // if the key cannot be resolved,
            // leave it alone ( and don't parse again )
            // else prefix the original string with the
            // resolved property ( so it can be parsed further )
            // taking recursion into account.
            if (nv == null || nv.equals(nk)) {
                ret += "${" + nk + "}";
            } else {
                v = nv + v;
            }
        }
        return ret + v;
    }

    //Begin: RS addition
    /**
     * Use various strategies to discover the file.
     */
    public Location getLocation(String path, MavenProject project) {
        LocatorStrategy classpathStrategy = new ClasspathResourceLocatorStrategy();

        List strategies = new ArrayList();
        strategies.add(classpathStrategy);
        strategies.add(new FileLocatorStrategy());
        strategies.add(new URLLocatorStrategy());

        List refStrategies = new ArrayList();
        refStrategies.add(classpathStrategy);

        Locator locator = new Locator();

        locator.setStrategies(strategies);

        Location location = locator.resolve(path);
        return location;
    }
    //End: RS addition
}

6
你是否曾将此作为补丁提交给Properties Maven插件?因为我也有类似的需求,我有一个在jar包中的属性文件,然后想使用maven-resources-plugin和一个xml文件进行过滤。 - Jay Blanton
这是一个很好的答案,但我遇到了一些麻烦。我有一个父POM,在其中从一个紧挨着它的文件中读取版本,并调用必要的设置方法。属性被设置了,但当解析依赖关系时,它们没有被使用... 我需要强制重新插值吗?我已经尝试过 project.getModel().setProperties(propectProperties),但没有成功。我真的希望这能够工作 :'( - niken

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接