[英]How does a Spring Boot console based application work?
如果我正在開發一個相當簡單的基於 Spring Boot 控制台的應用程序,我不確定主要執行代碼的位置。 我應該將它放在public static 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));
}
}
GreeterService.java (接口)
public interface GreeterService {
String greet(String[] tokens);
}
GreeterServiceImpl.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?
}
}
你應該有一個標准的加載器:
@SpringBootApplication
public class MyDemoApplication {
public static void main(String[] args) {
SpringApplication.run(MyDemoApplication.class, args);
}
}
並使用@Component
注釋實現CommandLineRunner
接口
@Component
public class MyRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
}
}
@EnableAutoConfiguration
將執行通常的 SpringBoot 魔法。
更新:
正如@jeton 所建議的,最新的 Springboot 實現了一個直接的:
spring.main.web-environment=false
spring.main.banner-mode=off
請參閱72.2 處的文檔
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.