Search code examples
javamavenmaven-pluginmaven-profiles

Maven Build Profile Activation


I know there are some related topics but still I can't understand how to do it.

I'm learning maven and currently in process of creating build profiles. I want maven to auto detect the currently installed java version on my machine. Let's say I'm working in our office which uses (jdk7) or home (jdk8), I want the <source> and <target> elements in maven-compiler-plugin pom.xml to auto detect the java -version regardless of environment (office / home). I've read about activation but can't perfectly understand the purpose.

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>   
            <configuration>
                <source>${jdk.version}</source>
                <target>${jdk.version}</target>
            </configuration>    
        </plugin>
    </plugins>
  </build>

Solution

  • Hi I don't think you can have your build, environment aware automatically, just using the defaults, you need some help of profiles and their activation capability see here. What you can do is introduce 2 different profiles, in each profile you can define the JDK you want, and it will be activated for your if present, then you can configure either the compiler plugin with different source /target or, just set different values for a a property that is going to indicate the java version. Example:

    <profiles>
     <profile>
         <id>java8</id>
         <activation>
           <jdk>1.8</jdk>
         </activation>
       <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>   
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>    
            </plugin>
        </plugins>
      </build>
       </profile>
    <profile>
         <id>java7</id>
         <activation>
           <jdk>1.7</jdk>
         </activation>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>   
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>    
            </plugin>
        </plugins>
      </build>
       </profile>
    </profiles>
    

    Hope that helps :)