Different maven compiler versions for test and main

前端 未结 3 1978
-上瘾入骨i
-上瘾入骨i 2020-12-13 13:49

How can I configure the maven compiler to use java 5 for my test code and java 1.4 for my main code?

3条回答
  •  暖寄归人
    2020-12-13 14:27

    I found a solution at least for my case.

    I am writing a library that needs to be Java 1.7 compatible but relies on the nashorn engine in JDK 8 to test some of its features, which is a perfect reason for using different compiler/jdk version for main and test.

    When talking about using different compiler/JRE version for main and test, say version A for main and version B for test and A is strictly smaller than B, we really want to achieve the following:

    1. Make the IDE (in my case, the Eclipse) use the JDK version B during development for not introducing compilation error (red cross on your project icon).
    2. Make JUnit tests runnable from within your IDE.
    3. Make JUnit tests runnable from command line through mvn clean test which is required for releasing.
    4. Compile sources in main using JRE A, which enables automatic detection of using new features from JDK B.
    5. Free use of new features / new APIs from JDK B in test cases codes.

    And the following pom declaration works (for example let A = 1.7 and B = 1.8):

                
                    org.apache.maven.plugins
                    maven-compiler-plugin
                    3.5.1
                    
                        true
                        1.8
                        1.8
                    
                    
                       
                          default-compile
                          
                             
                                1.7
                                1.7
                             
                          
                       
                       
                          default-testCompile
                          
                             
                                1.8
                                1.8
                             
                          
                       
                    
                
    

    Firstly, 1.8 1.8 is a must to make Eclipse happy and using 1.8 for the project itself, as others pointed out that Eclipse has a still pending bug and does not support different JDK version in a single project natively.

    Secondly, use to override the source and target arguments during source compilation and test source compilation. default-compile and default-testCompile are special names for compiler plugin.

    Thirdly, be sure to use compilerArguments but not compilerArgs. As far as I know, only compilerArguments can be used to override argument settings during runtime.

提交回复
热议问题