В Spring Boot для создания не веб-приложения реализует CommandLineRunner и переопределяет метод run , например:
import org.springframework.boot.CommandLineRunner;
@SpringBootApplication
public class SpringBootConsoleApplication implements CommandLineRunner {
public static void main(String[] args) throws Exception {
SpringApplication.run(SpringBootConsoleApplication.class, args);
}
//access command line arguments
@Override
public void run(String... args) throws Exception {
//do something
}
}
1. Структура проекта
Стандартная структура проекта Maven.
2. Зависимость от проекта
Только пружинный загрузочный стартер
4.0.0 com.mkyong spring-boot-simple jar 1.0 org.springframework.boot spring-boot-starter-parent 1.5.1.RELEASE 1.8 org.springframework.boot spring-boot-starter org.springframework.boot spring-boot-maven-plugin
3. Весна
3.1 Услуга по возврату сообщения.
package com.mkyong.service;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service
public class HelloMessageService {
@Value("${name:unknown}")
private String name;
public String getMessage() {
return getMessage(name);
}
public String getMessage(String name) {
return "Hello " + name;
}
}
name=mkyong
3.2 Командный запускатель пример. Если вы запустите эту весеннюю загрузку, точкой входа будет метод run .
package com.mkyong;
import com.mkyong.service.HelloMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.Banner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import static java.lang.System.exit;
@SpringBootApplication
public class SpringBootConsoleApplication implements CommandLineRunner {
@Autowired
private HelloMessageService helloService;
public static void main(String[] args) throws Exception {
//disabled banner, don't want to see the spring logo
SpringApplication app = new SpringApplication(SpringBootConsoleApplication.class);
app.setBannerMode(Banner.Mode.OFF);
app.run(args);
}
// Put your logic here.
@Override
public void run(String... args) throws Exception {
if (args.length > 0) {
System.out.println(helloService.getMessage(args[0].toString()));
} else {
System.out.println(helloService.getMessage());
}
exit(0);
}
}
4. ДЕМОНСТРАЦИЯ
Упакуйте и запустите его.
## Go to project directory ## package it $ mvn package $ java -jar target/spring-boot-simple-1.0.jar Hello mkyong $ java -jar target/spring-boot-simple-1.0.jar "donald trump" Hello donald trump
Скачать Исходный Код
Рекомендации
Оригинал: “https://mkyong.com/spring-boot/spring-boot-non-web-application-example/”