Can I compile and run a spring boot jar from inside another spring boot application

javaspringboot

It is generally not recommended to try to run a Spring Boot application inside another Spring Boot application. This is because each Spring Boot application is designed to run as a standalone application, with its own classloader and dependencies.

If you want to execute code from one Spring Boot application in another, you could consider using a different approach, such as calling a REST API or using a message queue to communicate between the two applications.

Alternatively, you could consider using an embedded application server, such as Apache Tomcat or Jetty, to run the second Spring Boot application inside the first. This would allow you to start and stop the second application as needed, while still keeping the two applications separate.

To use an embedded application server with Spring Boot, you can add the appropriate dependency to your project and use the SpringApplication.run() method to start the application. For example:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class MyApplication {

    public static void main(String[] args) {
        new SpringApplicationBuilder()
            .sources(MyApplication.class)
            .run(args);
    }

    @Bean
    public ServletWebServerFactory servletContainer() {
        return new TomcatServletWebServerFactory();
    }
}

This will start the second Spring Boot application using an embedded Tomcat server.

For more information on using embedded servers with Spring Boot, you can refer to the Spring Boot documentation: https://docs.spring.io/spring-boot/docs/current/reference/html/howto-embedded-servlet-containers.html.