基于Spring Boot控制台的应用程序如何工作?
2022-09-01 00:08:08
如果我正在开发一个相当简单的基于Spring Boot控制台的应用程序,我不确定主执行代码的位置。我应该把它放在公共静态 void main(String[] args)
方法中,还是让主应用程序类实现 CommandLineRunner
接口并将代码放在 run(String...args)
方法?
我将使用一个示例作为上下文。假设我有以下[基本]应用程序(编码为接口,Spring样式):
应用.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));
}
}
迎宾服务.java(接口)
public interface GreeterService {
String greet(String[] tokens);
}
迎宾服务.java(实现类)
@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;
}
}
Application.java
的等效Spring Boot版本将是这样的:GreeterServiceImpl.java(实现类)
@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?
}
}