Spring Bootの非Webアプリケーションの例
Spring Bootでは、非Webアプリケーションを作成するために、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. プロジェクトの依存関係
spring-boot-starterのみ
pom.xml
4.0.0 com.example 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 A service to return a message.
HelloMessageService.java
package com.example.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;
}
}
application.properties
name=example
3.2 CommandLineRunner example. このSpringBootを実行すると、runメソッドがエントリポイントになります。
SpringBootConsoleApplication.java
package com.example;
import com.example.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. DEMO
パッケージ化して実行します。
## Go to project directory ## package it $ mvn package $ java -jar target/spring-boot-simple-1.0.jar Hello example $ java -jar target/spring-boot-simple-1.0.jar "donald trump" Hello donald trump
ソースコードをダウンロード
ダウンロード–spring-boot-non-web-example.zip(5 KB)