53

私はmavenによって構築されたいくつかのプロジェクトを持っています.Springバージョン、mysqlドライバーバージョン、svnベースURLなど、それらの間でいくつかの共通プロパティを共有したいので、それらを一度更新するとすべてのプロジェクトに反映されます。

すべてのプロパティを備えた単一のスーパー pom を用意することを考えましたが、問題の 1 つを変更した場合は、そのバージョンをインクリメントする (およびそこから継承するすべての pom を更新する) か、すべての開発者のマシンから削除する必要があります。やりたくない。

これらのパラメーターを pom の外部で指定できますか? 親ポンに外部の場所の定義が必要です。

4

3 に答える 3

28

できることは、Properties Maven pluginを使用することです。これにより、外部ファイルでプロパティを定義できるようになり、プラグインはこのファイルを読み取ります。

この構成では:

<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 を変更せずに、これらのプロパティの値を変更します。
于 2009-08-05T07:04:15.207 に答える
14

私がここに持っている元のアイデアは私がやっているものですが、以下にリストしたより良いアイデアを見つけたかもしれないことに注意してください. 新しいアイデアが機能しない場合に備えて、完全を期すために両方のアイデアをここに残しておきたいと思いました。


親の pom を使用してこの問題を解決できると思いますが、maven リポジトリと CI ビルド ツールが必要です。

親POMから基本プロパティを継承するプロジェクトがいくつかあります。ここでは Java 1.5 を使用しているため、そこでビルド プロパティが設定されます。すべてUTF-8です。実行したいすべてのレポート、ソナーのセットアップなどは、親 POM 内にあります。

プロジェクトがバージョン管理されており、CI ツールがあると仮定すると、チェックインすると、CI ツールは POM プロジェクトをビルドし、SNAPSHOT を Maven リポジトリにデプロイできます。プロジェクトが親 POM の SNAPSHOT バージョンを指している場合、リポジトリをチェックして、最新バージョンがあることを確認します... そうでない場合は、最新バージョンをダウンロードします。したがって、親を更新すると、他のすべてのプロジェクトが更新されます。

トリックは、SNAPSHOT でリリースすることだと思います。リリースは、変更よりもはるかに少ない頻度で行われると思います。したがって、POM のリリースを実行してから、それらを継承する POM を更新し、バージョン管理にチェックインします。開発者に、更新を行う必要があることを知らせ、そこから先に進みます。

そこでビルドをトリガーして、新しい POM をリポジトリに強制し、すべての開発者がビルド時に変更を自動的に取得するようにすることができます。


親 POM では機能しないため、LATEST/RELEASE キーワードのアイデアを削除しました。それらは依存関係またはプラグインに対してのみ機能します。問題の領域は DefaultMavenProjectBuilder にあります。基本的に、最新またはリリース バージョンが何であるかを判断するために親を探すリポジトリを決定するのは困難です。ただし、これが依存関係またはプラグインで異なる理由はわかりません。


これらは、親POMへの変更ごとにPOMを更新するよりも苦痛が少ないようです。

于 2009-08-11T13:22:29.003 に答える
7

properties-maven-plugin は長期的には正しいアプローチだと思いますが、その回答に回答したように、プロパティを継承することはできません。maven-shared-io には、プロジェクトのクラスパスでリソースを検出できる機能がいくつかあります。プロパティ プラグインを拡張して、プラグインの依存関係でプロパティ ファイルを検索する以下のコードを含めました。

記述子プロジェクトはプラグイン構成で宣言されているため、構成はプロパティ ファイルへのパスを宣言し、ClasspathResourceLocatorStrategy にアクセスできます。構成は親プロジェクトで定義でき、すべての子プロジェクトに継承されます (これを行う場合、検出されないファイルを宣言することは避け、filePaths プロパティのみを設定してください)。

以下の構成では、name.seller.rich:test-properties-descriptor:0.0.1 という別の jar プロジェクトがあり、external.properties というファイルが jar にパッケージ化されている (つまり、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」プロパティを使用して、クラスパスで外部プロパティ ファイルへの相対パスを定義できるようにし、files プロパティをオプションにし、readPropertyFiles() と getLocation を追加します。 () メソッドを使用してファイルを検索し、すべての filePath を files 配列にマージしてから続行します。変更を明確にするために、変更をコメントしました。

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
}
于 2009-08-12T10:40:28.623 に答える