springboot-How to run a simple java application in spring boot application?
1. Purpose
In this post, I would demo how to setup and run a simple java application within sprinb boot application, this application will only depend on the core of spring boot framework, and it does not include the web/jdbc/jpa dependencies. It would be used only for testing the java (or JDK) language features.
2. Environment
- Spring boot
- Java 1.8 +
3. The problem and solution
3.1 The problem
When we want to do some java language testing, we can develop the program based on the spring boot application framework, but spring boot application does have many dependencies, just as the following picutre shows:
The pom.xml for the above dependency tree is:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
What if we don’t want the above dependenices? Just as the following picture shows, we only want the core of spring boot , e.g. the logging and auto-configuring of the app, hoow to remove those big dependencies and just contain the core of springboot?
3.2 Solution
We can define the pom.xml as follows:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
</dependencies>
Then we should create a main function in the app:
package com.bswen.plainjava;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class PlainJavaApp {
public static void main(String[] args) {
SpringApplication.run(PlainJavaApp.class, args);
}
}
Then we can write a simple java application as follows:
@Component
public class HelloWorld1 implements CommandLineRunner {
private static Log log = LogFactory.getLog(HelloWorld1.class);
@Override
public void run(String... args) throws Exception {
log.info("run a test function here");
}
}
Then run the app:
$ mvn spring-boot:run
We got this:
2021-07-07 12:57:39.868 INFO 13582 --- [ main] c.bswen.plainjava.commands.HelloWorld1 : run a test function here
4. Summary
In this post, I tried to demonstrate how to write simple java application based on spring boot application framework. The code can be found here: https://github.com/bswen/bswen-springboot24