Spring Boot Cli Hello World
Java has never had the easiest of Hello World programs. For the very simplest Hello World, we would have to create a class, define a static method within that class, and to display output, there’s a call to “System.out.println”:
public class MyMain {
public static void main(String args[]) {
System.out.println("Hello World");
}
}
That’s without the use of packages (namespaces), Maven, or the Spring framework.
Place the .java file in src/main/java and creating a pom.xml file with the Spring Boot dependency (below):
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>springBootTry</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.source>18</maven.compiler.source>
<maven.compiler.target>18</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>2.6.5</version>
</dependency>
</dependencies>
</project>
Add the @SpringBootApplication annotation to MyMain - this is a combination of the @Configuration, @EnableAutoConfiguration and @ComponentScan annotations.
To define the entry point, there are two approaches - implement the CommandLineRunner interface and override the run method, or create a method that returns a CommandLineRunner instance and annotate it with @Bean.
Approach 1:
package com.pockettheories;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MyMain implements CommandLineRunner {
public static void main(String args[]) {
SpringApplication.run(MyMain.class, args);
}
@Override
public void run(String... args) throws Exception {
System.out.println("Hello World");
}
}
Approach 2:
package com.pockettheories;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class MyMain {
public static void main(String args[]) {
SpringApplication.run(MyMain.class, args);
}
@Bean
public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
return args -> {
System.out.println("Hello World");
};
}
}