Search code examples
javaspringspring-bootmavenintellij-idea

IntelliJ Idea: How to run Spring Boot application which has a main class in the external dependency?


I am normally able to run a Spring Boot application (see the screen) if I am the one who defines the main class annotated with @SpringBootApplication.

enter image description here

Once I, however, have an extension module with a bunch of bean definitions and configurations, and the main class annotated by @SpringBootApplication is in an external dependency imported by Maven, then I am unable to locate such a class in the Run/Debug Configuration as it does not exist in my code-base. Let's name such a class com.mycompany.WhateverApplication.

On K8s, the application runs normally because of the Maven Spring Boot plugin that repackages the whole application.

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <configuration>
        <executable>true</executable>
        <mainClass>com.mycompany.WhateverApplication</mainClass>
    </configuration>
    <executions>
        <execution>
            <goals>
                <goal>repackage</goal>
            </goals>
        </execution>
    </executions>
</plugin>

How to run the application from IntelliJ Idea and how to create a valid Run/Debug Configuration?


Solution

  • Unfortunately, there is not direct solution provided by IntelliJ Idea, but I found two workarounds.

    Run the erroneous configuration anyway

    As long as the main class annotated by @SpringBootApplication is present on the classpath, typing the class name into the Spring Boot Run/Debug Configuration should work, though IntelliJ Idea marks the configuration as incomplete or erroneous.

    enter image description here

    Though it is not beautiful and the configuration icon looks scary, the application boots up: enter image description here


    Extend the class

    A more elegant solution is actually just extending the main class annotated by @SpringBootApplication to make it visible for IntelliJ Idea. In fact, nothing would change effectively for the application start-up and the Maven Spring Boot plugin does not need to (but can) be changed.

    package com.mycompany;
    
    import com.mycompany.WhateverApplication;
    
    public class ExtWhateverApplication extends WhateverApplication {
    
    }
    

    Now the application can be run directly from IntelliJ Idea as well as the Run/Debug Configuration. I recommend putting the new class in the same-named package as its parent.

    enter image description here

    enter image description here


    Note: In both cases, make sure the classpath -cp points to the extension module you want to run.