How does a Spring Boot console based application work?
If I am developing a rather simple Spring Boot console-based application, I am unsure about the placement of the main execution code. Should I place it in the public static void main(String[] args)
method, or have the main application class implement the CommandLineRunner
interface and place the code in the run(String... args)
method?
I will use an example as the context. Say I have the following [rudimentary] application (coded to interfaces, Spring style):
Application.java
public class Application {
@Autowired
private GreeterService greeterService;
public static void main(String[] args) {
// ******
// *** Where do I place the following line of code
// *** in a Spring Boot version of this application?
// ******
System.out.println(greeterService.greet(args));
}
}
GreeterService.java (interface)
public interface GreeterService {
String greet(String[] tokens);
}
GreeterServiceImpl.java (implementation class)
@Service
public class GreeterServiceImpl implements GreeterService {
public String greet(String[] tokens) {
String defaultMessage = "hello world";
if (args == null || args.length == 0) {
return defaultMessage;
}
StringBuilder message = new StringBuilder();
for (String token : tokens) {
if (token == null) continue;
message.append(token).append('-');
}
return message.length() > 0 ? message.toString() : defaultMessage;
}
}
The equivalent Spring Boot version of Application.java
would be something along the lines:
GreeterServiceImpl.java (implementation class)
@EnableAutoConfiguration
public class Application
// *** Should I bother to implement this interface for this simple app?
implements CommandLineRunner {
@Autowired
private GreeterService greeterService;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
System.out.println(greeterService.greet(args)); // here?
}
// Only if I implement the CommandLineRunner interface...
public void run(String... args) throws Exception {
System.out.println(greeterService.greet(args)); // or here?
}
}
Solution 1:
You should have a standard loader:
@SpringBootApplication
public class MyDemoApplication {
public static void main(String[] args) {
SpringApplication.run(MyDemoApplication.class, args);
}
}
and implement a CommandLineRunner
interface with @Component
annotation
@Component
public class MyRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
}
}
@EnableAutoConfiguration
will do the usual SpringBoot magic.
UPDATE:
As @jeton suggests the latest Springboot implements a straight:
spring.main.web-application-type=none
spring.main.banner-mode=off
See docs at 72.2