문제

저는 maven으로 빌드한 여러 프로젝트를 가지고 있으며 스프링 버전, mysql 드라이버 버전, svn 기본 URL 등 몇 가지 공통 속성을 공유하고 싶습니다.- 한번 업데이트하면 모든 프로젝트에 반영됩니다.

모든 속성이 포함된 단일 슈퍼 폼을 만들려고 생각했지만 문제 중 하나를 변경하면 해당 버전을 늘리거나(그리고 여기서 상속하는 모든 폼을 업데이트해야 함) 모든 개발자 컴퓨터에서 삭제해야 합니다. 나는하고 싶지 않습니다.

이러한 매개변수를 pom 외부에서 지정할 수 있나요?나는 여전히 상위 pom에 외부 위치 정의를 갖고 싶습니다.

도움이 되었습니까?

해결책

내가 여기에있는 원래 아이디어는 내가하고있는 일이지만 아래에 나열된 훨씬 더 나은 아이디어를 찾았을 수도 있습니다. 새로운 아이디어가 할 경우를 대비하여 완전성을 위해 두 아이디어를 모두 여기에두고 싶었습니다. ~ 아니다 일하다.


부모 POM을 사용 하여이 문제를 해결할 수 있다고 생각하지만 Maven 저장소와 CI 빌드 도구가 필요합니다.

부모님 POM의 기본 속성을 상속하는 여러 프로젝트가 있습니다. 우리는 Java 1.5를 사용하므로 빌드 속성이 설정됩니다. 모든 것이 UTF-8입니다. 내가 실행하고 싶은 모든 보고서, Sonar 설정 등은 부모 Pom 내부에 있습니다.

프로젝트가 버전 제어 중이고 CI 도구가 있다고 가정하면 체크인하면 CI 도구가 POM 프로젝트를 작성하고 스냅 샷을 Maven Repos에 배포 할 수 있습니다. 프로젝트가 Parent Pom의 스냅 샷 버전을 가리키면 리포지토리를 확인하여 최신 버전이 있는지 확인합니다. 따라서 부모를 업데이트하면 다른 모든 프로젝트가 업데이트됩니다.

트릭은 스냅 샷으로 공개하는 것입니다. 나는 당신의 릴리스가 당신의 변화보다 훨씬 덜 자주 올 것이라고 말하고 싶습니다. 따라서 POM을 출시 한 다음 POM을 상속받는 POM을 업데이트하여 버전 제어에 확인하십시오. 개발자에게 업데이트를하고 그곳에서 가야한다는 것을 알리십시오.

새 poms를 저장소에 강제로 만들어 빌드를 트리거 한 다음 빌드시 자동으로 변경 사항을 선택할 수 있습니다.


최신/릴리스 키워드 아이디어가 부모 Poms에서 작동하지 않기 때문에 제거했습니다. 종속성이나 플러그인 만 작동합니다. 문제 영역은 DefaultMavenProjectBuilder에 있습니다. 기본적으로 부모가 최신 또는 릴리스 버전이 무엇인지 결정할 리포지토리를 결정하는 데 어려움이 있습니다. 그래도 종속성이나 플러그인에 대해 왜 다른지 확실하지 않습니다.


부모님 POM에 대한 모든 변화에 따라 POM을 업데이트하는 것보다 이것들이 덜 고통 스러울 것 같습니다.

다른 팁

당신이 할 수있는 것은 사용하는 것입니다 속성 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을 수정하지 않고 이러한 특성의 값을 수정하십시오.

나는 Properties-maven-plugin이 장기적으로 올바른 접근 방식이라고 생각하지만 해당 답변에 응답하면 속성 상속이 허용되지 않습니다.maven-shared-io에는 프로젝트 클래스 경로에서 리소스를 검색할 수 있는 몇 가지 기능이 있습니다.아래에는 플러그인의 종속성에서 속성 파일을 찾기 위해 속성 플러그인을 확장하는 일부 코드가 포함되어 있습니다.

설명자 프로젝트는 플러그인 구성에서 선언되므로 ClasspathResourceLocatorStrategy에 액세스할 수 있으므로 구성은 속성 파일에 대한 경로를 선언합니다.구성은 상위 프로젝트에서 정의할 수 있으며 모든 하위 프로젝트에서 상속됩니다(이렇게 하면 파일이 검색되지 않으므로 파일을 선언하지 말고 filePaths 속성만 설정하세요).

아래 구성에서는 jar에 패키지된 external.properties라는 파일이 있는 name.seller.rich:test-properties-descriptor:0.0.1이라는 또 다른 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는 클래스 경로의 외부 속성 파일에 대한 상대 경로를 정의할 수 있는 추가 "filePaths" 속성이 있는 속성 플러그인의 ReadPropertiesMojo의 복사본이며, 파일 속성을 선택 사항으로 만들고 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
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top