Using the Maven Compiler plugin

Compilation is an essential task performed by a build tool. Maven uses the Maven Compiler plugin to do the compilation. The plugin provides several configurations to make the compilation flexible.

How to do it...

To use the Maven Compiler plugin, perform the following steps:

  1. Open a command prompt.
  2. Run the following Maven command on the simple project that we created in the Creating a simple project with Maven recipe in Chapter 1, Getting Started:
    mvn compile
    
  3. Observe the output, which is as follows:
    [INFO] --- maven-compiler-plugin:2.3.2:compile (default-compile) @ simple-project ---
    [INFO] Compiling 1 source file to C:projectsapache-maven-cookbooksimple-project	argetclasses
    

How it works...

The compile parameter indicates the invocation of the default lifecycle to Maven. As illustrated in the Understanding the Maven lifecycle, phases, and goals recipe in Chapter 3, Maven Lifecycle, Maven runs all the phases up to and including the compile phase in order.

The compile phase itself essentially runs the compile goal of the Maven Compiler plugin.

This compiles the Java source files to classes in the target/classes folder.

One question would have struck you. What about the test classes? Why does the compile phase not compile the test sources?

The answer lies in the way Maven handles the lifecycle and phases of the lifecycle. Why would you want to compile the test sources unless you want to run the tests?

There's more...

What if we want to compile the test sources?

Let us try running the following command on the command prompt:

mvn test

Observe the output as shown in the following screenshot:

There's more...

As we specified the test phase, Maven ran all phases prior to it, which includes compiling the test sources using the testCompile goal of the Maven Compiler plugin.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.78.237