1. Overview

In this tutorial, we’ll run Java code through Maven with JVM arguments. We’ll explore how to apply those arguments to the build globally and then focus on applying them to specific Maven plugins.

2. Setting up Global JVM Arguments

First, we’ll see two different techniques for applying JVM arguments to the main Maven process.

2.1. Using Command-Line

To run a Java Maven project with JVM arguments, we’ll set the MAVEN_OPTS environment variable. This variable contains the parameters to use on JVM start-up and allows us to supply additional options:

$ export MAVEN_OPTS="-Xms256m -Xmx512m"

In this example, we define the minimal and maximal heap sizes through MAVEN_OPTS. Then, we can run our build via:

$ mvn clean install

The arguments we set up apply to the main process of the build.

2.2. Using the jvm.config File

An alternative to set up global JVM arguments automatically is to define a jvm.config file. We must locate this file in a .mvn folder at the root of our project. The content of the file is the JVM parameters to apply. For example, to mimic the command line we used previously, our configuration file would read:

-Xms256m -Xmx512m

3. Setting JVM Arguments to a Specific Plugin

Maven plugins may fork new JVM processes to execute their task. Thus, setting up global arguments doesn’t work with them. Every plugin defines its way of setting up the arguments, but most configurations look alike. In particular, we’ll showcase examples of three widely used plugins: the spring-boot Maven plugin, the surefire plugin, and the failsafe plugin.

3.1. Setup Example

Our idea is to set up a basic Spring project, but we want the code to be runnable only when we set some JVM argument.

Let’s start by writing our service class:

@Service
class MyService {
    int getLength() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
        ArrayList<String> arr = new ArrayList<>();
        Field sizeField = ArrayList.class.getDeclaredField("size");
        sizeField.setAccessible(true);
        return (int) sizeField.get(arr);
    }
}

The introduction of the module system in Java 9 brought more restrictions to reflective access. Thus, this piece of code compiles in Java 8 but requires adding the –add-open JVM option to open the java-util package of the java-base module for reflection in Java 9 and later.

Now, we can add a straightforward controller class on top of it:

@RestController
class MyController {
    private final MyService myService;

    public MyController(MyService myService) {
        this.myService = myService;
    }

    @GetMapping("/length")
    Integer getLength() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
        return myService.getLength();
    }
}

To finish our setup, let’s add the main application class:

@SpringBootApplication
public class MyApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

3.2. Spring-Boot Maven Plugin

Let’s add the base configuration of the latest version of Maven’s spring-boot plugin:

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <version>3.3.0</version>
</plugin>

We can now run the project via the following command:

$ mvn spring-boot:run

As we can see, the application starts successfully. However, when we try to make a GET request on http://localhost:8080/length, we get an error associated with the following log:

java.lang.reflect.InaccessibleObjectException: Unable to make field private int java.util.ArrayList.size accessible: module java.base does not "opens java.util" to unnamed module

As we said during setup, we must add some reflection-related JVM arguments to avoid this error. In particular, for the spring-boot Maven plugin, we need to use the jvmArguments configuration tag:

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <version>3.3.0</version>
    <configuration>
        <jvmArguments>--add-opens java.base/java.util=ALL-UNNAMED</jvmArguments>
    </configuration>
</plugin>

We can now re-run the project: the GET request on http://localhost:8080/length now returns 0, the expected answer.

3.3. Surefire Plugin

First, let’s add a unit test for our service:

class MyServiceUnitTest {
    MyService myService = new MyService();
    
    @Test
    void whenGetLength_thenZeroIsReturned() throws NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
        assertEquals(0, myService.getLength());
    }
}

The Surefire plugin is commonly used to run unit tests through Maven. Let’s naively add the base configuration of the latest version of the plugin:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>3.3.0</version>
    <configuration>
        <includes>
            <include>**/*UnitTest.java</include>
        </includes>
    </configuration>
</plugin>

The shortest way to run our unit tests via Maven is to run the following command:

$ mvn test

We can see that our test is failing with the same error we got previously! Nevertheless, with the surefire plugin, the correction lies in setting the argLine configuration tag:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>3.3.0</version>
    <configuration>
        <includes>
            <include>**/*UnitTest.java</include>
        </includes>
        <argLine>--add-opens=java.base/java.util=ALL-UNNAMED</argLine>
    </configuration>
</plugin>

Our unit tests can now run successfully!

3.4. Failsafe Plugin

We’ll now write an integration test for our controller:

@SpringBootTest(classes = MyApplication.class)
@AutoConfigureMockMvc
class MyControllerIntegrationTest {
    @Autowired
    private MockMvc mockMvc;

    @Test
    void whenGetLength_thenZeroIsReturned() throws Exception {
        mockMvc.perform(MockMvcRequestBuilders.get("/length"))
          .andExpect(MockMvcResultMatchers.status().isOk())
          .andExpect(MockMvcResultMatchers.content().string("0"));
    }
}

Generally, we use the failsafe plugin to run integration tests through Maven. Once again, let’s set it up with the base configuration of its latest version:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-failsafe-plugin</artifactId>
    <version>3.3.0</version>
    <executions>
        <execution>
            <goals>
                <goal>integration-test</goal>
                <goal>verify</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <includes>
            <include>**/*IntegrationTest.java</include>
        </includes>
    </configuration>
</plugin>

Let’s now run our integration tests:

$ mvn verify

Without any surprise, our integration test fails for the same error that we already experienced. The correction for the failsafe plugin is identical to the one for the surefire plugin. We must use the argLine configuration tag to set the JVM argument:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-failsafe-plugin</artifactId>
    <version>3.3.0</version>
    <executions>
        <execution>
            <goals>
                <goal>integration-test</goal>
                <goal>verify</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <includes>
            <include>**/*IntegrationTest.java</include>
        </includes>
        <argLine>--add-opens=java.base/java.util=ALL-UNNAMED</argLine>
    </configuration>
</plugin>

The integration test will now run with success.

4. Conclusion

In this article, we learned how to use JVM arguments when running Java code in Maven. We’ve explored two techniques to set global arguments to the build. Then, we saw how to pass JVM arguments to some of the most used plugins. Our examples were not exhaustive, but, in general, other plugins work very similarly. To recap, we can always refer to a plugin documentation to know exactly how to configure it.

As always, the code is available over on GitHub.