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?
}
}
CommandLineRunner
that is what is it designed for, you can also create an instance of it and have dependencies injected into it. This would fail in your first scenario as you would not have a dependency injected or wouldn't be able to access it from the static method.Application
class). It has to do with separation of concerns (starting your application and executing your logic).GreeterService
[implementation] bean? Because myApplication
class only uses this service. So there is a separation of concern at this point already, no?Application
class to implement theCommandLineRunner
interface. You probably don't want this but do that in a separate class instead.