Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running spring boot with multiple main classes

Tags:

spring-boot

Currently in our application we have multiple main classes and executing them individually using below commands separately.

java -Xmx1024M -cp /path/to/jar/MyApp.jar com.....MyAppMain1

java -Xmx1024M -cp /path/to/jar/MyApp.jar com.....MyAppMain2

java -Xmx1024M -cp /path/to/jar/MyApp.jar com.....MyAppMain3

Now trying to use spring boot. What do we do to achieve the same?

In pom.xml have

…….
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.8.RELEASE</version>
    </parent>

……..

using spring boot and executing the command

java -Xmx1024M -cp /path/to/jar/MyApp.jar com.....MyAppMain1

getting error as [ERROR] Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.6.0:java (default-cli) on project MyApp:The parameters 'mainClass' for goal org.codehaus.mojo:exec-maven-plugin:1.6.0:java are missing or invalid

like image 780
opai Avatar asked Sep 16 '19 14:09

opai


People also ask

How do I run multiple main classes in spring boot?

Spring Boot allows us to define the Main class in the configuration when we have multiple main classes declared in the application. As we are using a MAVEN build, we have to configure the POM. xml for Spring Boot to identify the main class of the application. Voila!

Can we have 2 main classes in a spring boot application?

If Spring Boot project contains multiple main classes, Spring Boot will fail to start or packag for deployment.

Can we have more than one @SpringBootApplication?

In this example we are having two SpringBoot applications that we want to merge into one and for that we will create a new SpringBoot application for package them both and add the two old applications as maven dependencies. Then we will ask Spring to boot-up the application.


1 Answers

Spring Boot gives several ways:

  • specify main class as system property:
java -cp app.jar -Dloader.main=com.company.MyAppMain1 org.springframework.boot.loader.PropertiesLauncher
  • configure main class in Maven pom.xml <properties> section:
<properties>
  <start-class>com.company.MyAppMain1</start-class>
</properties>

Note that this property will only be evaluated if you use spring-boot-starter-parent as <parent> in your pom.xml.

  • configure main class for spring-boot-maven-plugin:
<build>
  <plugins>
    <plugin>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-maven-plugin</artifactId>             
      <configuration>    
        <mainClass>${start-class}</mainClass>
      </configuration>
    </plugin>
  </plugins>
</build>

Note: plugin configuration can be performed in Maven profile, so by activating different profiles, you'll run app with different main class.

like image 120
Oleksii Zghurskyi Avatar answered Sep 29 '22 05:09

Oleksii Zghurskyi