Spring Boot made command apps more popular, so in this post we’re going to show how in Maven run Java app from command line.
Sample Java program
Let’s create a simple Spring Boot application that will serve our testing purposes.
Maven pom.xmlns
Place the following POM inside a directory:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="https://maven.apache.org/POM/4.0.0"> <modelVersion>4.0.0</modelVersion> <groupId>com.farenda.tutorials</groupId> <artifactId>spring</artifactId> <version>0.0.1-SNAPSHOT</version> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>1.4.1.RELEASE</version> </dependency> </dependencies> <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>${java.version}</source> <target>${java.version}</target> </configuration> </plugin> </plugins> </build> </project>
Java code for Spring Boot app
Put the following code in src/main/java/com/farenda/tutorials/spring/App.java:
package com.farenda.tutorials.spring; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class App { public static void main(String[] args) throws Exception { System.out.println("Hello, Maven!"); SpringApplication.run(App.class, args); } }
That’s it! Spring Boot requires nothing else to start!
Maven exec plugin
Now, let’s execute the above application using Maven exec plugin:
mvn exec:java -Dexec.mainClass=com.farenda.tutorials.spring.App
When you run the above command, Maven will do processing and eventually run the app:
//... cut for brevity [INFO] --- exec-maven-plugin:1.4.0:java (default-cli) @ spring --- Hello, Maven! . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v1.4.1.RELEASE) 2016-11-06 18:21:35.920 INFO 22922 --- [ring.App.main()] com.farenda.tutorials.spring.App : Starting App on namek with PID 22922 (/home/przemek/poligon/java/spring/springboothw/target/classes started by przemek in /home/przemek/poligon/java/spring/springboothw) 2016-11-06 18:21:35.952 INFO 22922 --- [ring.App.main()] com.farenda.tutorials.spring.App : No active profile set, falling back to default profiles: default ...