LoginSignup
0
1

コピペで始める Spring Boot

Last updated at Posted at 2019-02-26

Spring Bootをいちから始めるヒト向けに、とりあえずコピペしたらなんか動く、ってのを目標に記事にしてみます。基本 Building a RESTful Web Service を参考にしています。

この記事のソースコード

基本この記事を実施すれば、動くSpring Bootのコードが得られますが、既に作成済みのソースをのせておきます。

環境

$ sw_vers
ProductName:	Mac OS X
ProductVersion:	10.14.3
BuildVersion:	18D109
$ mvn --version
Apache Maven 3.6.0 (97c98ec64a1fdfee7767ce5ffb20918da4f719f3; 2018-10-25T03:41:47+09:00)
Maven home: /usr/local/Cellar/maven/3.6.0/libexec
Java version: 1.8.0_25, vendor: Oracle Corporation, runtime: /Library/Java/JavaVirtualMachines/jdk1.8.0_25.jdk/Contents/Home/jre
Default locale: ja_JP, platform encoding: UTF-8
OS name: "mac os x", version: "10.14.3", arch: "x86_64", family: "mac"
$

いわゆるふつうのMacですが、Mavenさえあれば Windowsでもほぼ同じ手順で動かせると思います。

あと疎通をcurlでおこないます。

$ curl --version
curl 7.54.0 (x86_64-apple-darwin18.0) ...
$

やってみる

まず pom.xmlを下記からコピペで作成しましょう。

$ mkdir myproject && cd $_
$ cat pom.xml
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>myproject</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.3.RELEASE</version>
    </parent>

    <!-- Additional lines to be added here... -->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

    <!-- (you don't need this if you are using a .RELEASE version) -->
    <repositories>
        <repository>
            <id>spring-snapshots</id>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots><enabled>true</enabled></snapshots>
        </repository>
        <repository>
            <id>spring-milestones</id>
            <url>https://repo.spring.io/milestone</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-snapshots</id>
            <url>https://repo.spring.io/snapshot</url>
        </pluginRepository>
        <pluginRepository>
            <id>spring-milestones</id>
            <url>https://repo.spring.io/milestone</url>
        </pluginRepository>
    </pluginRepositories>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

sourceとpropertiesファイルを配置するディレクトリを作成します。

$ mkdir -p src/main/java
$ mkdir -p src/main/resources

Spring Bootを起動するおまじないが書いたファイルを作成します。

$ cat src/main/java/nu/mine/kino/springboot/SampleTomcatApplication.java
SampleTomcatApplication.java
package nu.mine.kino.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SampleTomcatApplication {
    
	public static void main(String[] args) {
		SpringApplication.run(SampleTomcatApplication.class, args);
	}

}

WEB機能を記述した、下記のControllerを作成します。

$ cat src/main/java/nu/mine/kino/springboot/GreetingController.java
GreetingController.java
package nu.mine.kino.springboot;

import java.util.concurrent.atomic.AtomicLong;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GreetingController {

    private static final String template = "Hello, %s!";

    private final AtomicLong counter = new AtomicLong();

    @RequestMapping("/greeting")
    public Greeting greeting(
            @RequestParam(value = "name", defaultValue = "World") String name) {
        return new Greeting(counter.incrementAndGet(),
                String.format(template, name));
    }
}

class Greeting {

    private final long id;

    private final String content;

    public Greeting(long id, String content) {
        this.id = id;
        this.content = content;
    }

    public long getId() {
        return id;
    }

    public String getContent() {
        return content;
    }
}

環境設定を記述する、propertiesファイルを作成します。

$ cat src/main/resources/application.properties
application.properties
server.compression.enabled: true
server.compression.min-response-size: 1
server.connection-timeout=5000
server.port=8080
server.address=0.0.0.0

server.portは起動するポート番号。デフォルトの8080でよければ実際は記述不要です。
server.addressは他のマシンからも繋がるようにするためのおまじないです。

起動

さあ、起動しましょう。

$ pwd
/xxxxx/xxx/myproject

$ mvn spring-boot:run

ばばーーっていろいろ表示されて、、
...
2019-02-26 14:03:46.797  INFO 40644 --- [           main] n.m.k.s.SampleTomcatApplication          : 
Started SampleTomcatApplication in 4.749 seconds (JVM running for 11.845)

ってでてればOK!

起動したら別のプロンプトから疎通してみます。

$ curl http://localhost:8080/greeting
{"id":1,"content":"Hello, World!"}
$

めでたく動きましたね!

起動したSpring BootのWEBサーバ(Tomcatですが)は Ctrl-Cなどで止めてあげましょう。
おつかれさまでした。

おまけ

jar化する

$ mvn clean package

で、Tomcat込みの実行可能なjarファイルができます。

$ java -jar target/myproject-0.0.1-SNAPSHOT.jar

とすることで、先のmvn spring-boot:run と同じようにTomcatが起動します。。

Eclipseで読み込む

$ mvn eclipse:clean eclipse:eclipse

で .project/.classpath ファイルが出来るのでEclipseにインポートできるようになります。

戻り値のJSONを整形して返すようにする

application.properties に以下の設定を追加します。

$ cat src/main/resources/application.properties
application.properties
...
spring.jackson.serialization.indent-output=true

Ctrl-Cして mvn spring-boot:run で再起動してからcurlで繋いでみると、、、

$ curl http://localhost:8080/greeting
{
  "id" : 1,
  "content" : "Hello, World!"
}

JSONが整形されました。。

関連リンク

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1