Jeśli opracowuję raczej prostą aplikację konsolową Spring Boot, nie jestem pewien co do położenia głównego kodu wykonawczego. Należy umieścić go w metodzie public static void main(String[] args)
, lub główny wniosek klasy implementują interfejs CommandLineRunner
i umieścić kod w metodzie run(String... args)
?Jak działa konsola Spring Boot?
Użyję przykładu jako kontekstu. Powiedzieć, że mają następujący [podstawową] Zgłoszenie (zakodowany interfejsów, Spring stylu):
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 (interfejs)
public interface GreeterService {
String greet(String[] tokens);
}
GreeterServiceImpl.java (klasa realizacja)
@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;
}
}
Równowartość wersja Wiosna Boot Application.java
byłoby coś wzdłuż linii: GreeterServiceImpl.java (klasa realizacja)
@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?
}
}
użyć 'CommandLineRunner' czyli co to jest przeznaczone do, można również tworzyć jest jego instancją i ma wstrzyknięte do niego zależności. W twoim pierwszym scenariuszu nie udałoby się tego, ponieważ nie miałbyś wstrzykniętej zależności lub nie byłbyś w stanie uzyskać do niej dostępu z metody statycznej. –
@ M.Deinum, więc takie aplikacje oparte na konsoli muszą implementować interfejs CommandLineRunner jako ogólną regułę? To zapewnia mi wystarczającą jasność, ponieważ nawet dokumenty nie koncentrują się na tej kwestii (prawdopodobnie dlatego, że jest to nieodłączne dla większości ludzi!). –
Idealnie tworzysz komponent bean, który implementuje ten interfejs (a nie twoją klasę "Application"). Ma to związek z rozdzielaniem spraw (uruchamianie aplikacji i wykonywanie logiki). –