Активация профиля maven на основе множества свойств

Я создаю сборку maven 2 для проекта, и я придумал профили, так как сборка должна быть создана как для разных мест (скажем, Берлин, Париж, Северный полюс), так и для разных условий (разработка, производство). Они указываются через свойства. Поэтому для "Северного полюса "" DEV " я делаю:

-Dlocation=NorthPole -Denvironment=DEV

теперь я хотел бы оживить мой porfile на основе обоих этих свойств, а не только одного. Поэтому я попытался следовать:

<profiles>
  <profile>
    <id>NOrth Pole DEV</id>
    <activation>
      <property>
        <name>location</name>
        <value>NorthPole</value>
      </property>
      <property>
        <name>environment</name>
        <value>DEV</value>
      </property>
    </activation>
    ... <!-- Set some North Pole DEV specific stuff -->
  </profile>
</profiles>

Это не работает, maven ожидает см.максимум один <property> элемент есть.

обратите внимание, что у меня есть другое использование для свойств, а также сделать его одним свойством locationEnvстоимостью NorthPole-DEV не то, что я хочу иметь.

Итак, есть ли способ или обходной путь или что-то еще, как активировать профиль на основе комбинации свойств?

6 ответов


почему бы не использовать профиль прямо как:

<profiles>
   <profile>
    <id>north-pole</id>
    <activation>
      <activeByDefault>false</activeByDefault>
    </activation>
    ....
  </profile>
   <profile>
    <id>dev</id>
    <activation>
      <activeByDefault>false</activeByDefault>
    </activation>
    ....
  </profile>
</profiles>

теперь вы можете активировать профили с помощью командной строки.

mvn -Pdev,north-pole ...

Я боюсь, что нет хорошего решения вашей проблемы (если нет новых функций Maven, о которых я не знаю).

теоретически вы можете ввести производное свойство, значение которого объединено из двух перечисленных вами свойств. Однако проблема заключается в том, что профили оцениваются до свойств, определенных в pom, поэтому такое производное свойство не может использоваться для активации профиля : - (

лучшее решение я могу думать, то подобная проблема была активируйте профиль явно и поместите различные комбинации параметров командной строки в отдельные файлы пакета/сценария, чтобы упростить выполнение и избежать ошибок.


Возможное Решение

попробуйте это расширение:https://github.com/kpiwko/el-profile-activator-extension

Это позволяет иметь такой синтаксис:

<profile>
    <id>NOrth Pole DEV</id>

    <activation>
        <property>
            <!-- mvel property name is obligatory -->
            <name>mvel</name>
            <value>isdef location &amp;&amp; location=="NorthPole" &amp;&amp; 
                   isdef environment &amp;&amp; environment=="DEV"</value>
        </property>
    </activation>
</profile>

Я сам не пробовал, но, кажется, хороший проект.

Как избежать ручной настройки Maven

вам нужно поместить необходимые две банки проекта в $MAVEN_HOME/lib / ext. Однако их можно автоматизировать. Как это:

  • вы можете добавить профиль, который составляет активировать в отсутствие of $MAVEN_HOME/lib/ext/el-профиль-активатор-расширение.jar-файл
  • этот профиль может загружать банки из maven с помощью плагин зависимостей в папку $MAVEN_HOME/lib/ext в фазе инициализации
  • затем вы можете написать сообщение, что сборка настроила папку maven, и следующая сборка будет успешной.

проверено профиль:

<profile>
    <id>prepare-maven-extended-libs</id>
    <activation>
      <file>
        <missing>${maven.home}/lib/ext/el-profile-activator-extension.jar</missing>
      </file>
    </activation>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.8</version>
                <executions>
                    <execution>
                        <id>copy</id>
                        <phase>validate</phase>
                        <goals>
                            <goal>copy</goal>
                        </goals>
                        <configuration>
                            <artifactItems>
                                <artifactItem>
                                    <groupId>com.redhat.jboss.maven</groupId>
                                    <artifactId>el-profile-activator-extension</artifactId>
                                    <version>1.0.0-SNAPSHOT</version>
                                    <type>jar</type>
                                    <overWrite>true</overWrite>
                                    <outputDirectory>${maven.home}/lib/ext</outputDirectory>
                                    <destFileName>el-profile-activator-extension.jar</destFileName>
                                </artifactItem>
                                <artifactItem>
                                    <groupId>org.mvel</groupId>
                                    <artifactId>mvel2</artifactId>
                                    <version>2.1.3.Final</version>
                                    <type>jar</type>
                                    <overWrite>true</overWrite>
                                    <outputDirectory>${maven.home}/lib/ext</outputDirectory>
                                    <destFileName>mvel2.jar</destFileName>
                                </artifactItem>
                            </artifactItems>
                            <outputDirectory>${project.build.directory}/wars</outputDirectory>
                            <overWriteReleases>true</overWriteReleases>
                            <overWriteSnapshots>true</overWriteSnapshots>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.codehaus.gmaven</groupId>
                <artifactId>gmaven-plugin</artifactId>
                <version>1.4</version>
                <executions>
                    <execution>
                        <phase>validate</phase>
                        <goals><goal>execute</goal></goals>
                    </execution>
                </executions>
                <configuration>
                    <source>
                        fail("For profile activation we use an extension jar. It is now in your ${maven.home}/lib/ext folder. Please restart the build, and then it will be successful.")
                    </source>
                </configuration>
            </plugin>               
        </plugins>
    </build>
</profile>

ответ хмарбеза кажется мне более элегантным. Комментировать Яна, вы можете обратиться к файлу, добавив свойства например, с профилем dev, Северный полюс активирован вы можете обратиться к NorthPole-dev.xml с ${location} - ${env}.XML.

Мне пришлось опубликовать другой ответ, поскольку я не могу добавлять комментарии к ответам других. :(


Я верю, что вы можете сделать что-то вроде этого

<properties>
        <env>dev</env>
        <location>North Pole</location>
    </properties>

<profiles>
        <!-- dev North Profile -->
        <profile>
            <id>dev North Pole</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
        </profile>
        <!-- qa North Profile -->
        <profile>
            <id>qa North Pole</id>
            <properties>
                         <env>qa</env>
                             <location>North Pole</location>
            </properties>
        </profile>

    </profiles>
<build>
do profile specific stuff here
</build>

of couse, для активации профиля вы можете добавить команду '- P=dev North Pole'


после исчерпывающего исследования я опубликовал видео, где я объясняю использование профилей Maven в среде с Spring Boot. Это проект spring boot rest, который обрабатывает свойства приложения для каждой среды с помощью профилей Maven.

вот ссылки:

Youtube:https://youtu.be/UbDpvh3YvDw

Github:https://github.com/carlosCharz/mavenprofilespringboot

код фрагмент:

Параметры Приложения

таможни.server_url = @custom.server_url@

таможни.server_port = @custom.server_port@

таможни.debuggable = @custom.debuggable@

таможни.image_quality = высокий

переопределяет параметры

таможни.server_url = api-dev.yourserver.com

таможни.server_port = 80

таможни.отлаживаемых = правда

<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/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.wedevol</groupId>
<artifactId>mvnspringboot</artifactId>
<version>1.0.0</version>
<packaging>war</packaging>
<name>Spring Boot Project with Maven</name>
<description>This is a spring boot rest project that handle the application properties per environment using Maven profiles.</description>

<properties>
    <java.version>1.8</java.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.0.RELEASE</version>
    <!-- https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.0-Release-Notes -->
</parent>

<dependencies>
    <!-- Spring -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>
</dependencies>

<!-- Maven profile per environment -->
<profiles>
    <profile>
        <id>local</id>
        <activation>
           <activeByDefault>true</activeByDefault>
        </activation>
        <properties>
            <overrides.props.file>local.overrides.properties</overrides.props.file>
            <current.profile>local</current.profile>
        </properties>
    </profile>
    <profile>
        <id>dev</id>
        <properties>
            <overrides.props.file>dev.overrides.properties</overrides.props.file>
            <current.profile>dev</current.profile>
        </properties>
    </profile>
    <profile>
        <id>qa</id>
        <properties>
            <overrides.props.file>qa.overrides.properties</overrides.props.file>
            <current.profile>qa</current.profile>
        </properties>
    </profile>
    <profile>
        <id>prod</id>
        <properties>
            <overrides.props.file>prod.overrides.properties</overrides.props.file>
            <current.profile>prod</current.profile>
        </properties>
    </profile>
</profiles>

<build>
    <finalName>mvnspringboot</finalName>
    <!-- Maven Resources. It handles the copying of project resources to the output directory. -->
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
            <excludes>
                <exclude>profiles/*</exclude>
            </excludes>
        </resource>
    </resources>
    <!-- Maven filtering. The variables are included in the resources ( ${..} or @...@ delimiters) -->
    <filters>
        <filter>src/main/resources/profiles/${overrides.props.file}</filter>
    </filters>
    <plugins>
        <!-- Spring boot maven plugin -->
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <!-- Ant plugin to print the current maven profile -->
        <plugin>
            <artifactId>maven-antrun-plugin</artifactId>
            <executions>
                <execution>
                    <phase>generate-resources</phase>
                    <goals>
                        <goal>run</goal>
                    </goals>
                    <configuration>
                        <tasks>
                            <echo>Current maven active profile: ${current.profile}</echo>
                        </tasks>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

Дайте мне знать, если он работал! Гростиньш!