用复制粘贴的方式开始Spring Boot

为了那些想要从头开始学习Spring Boot的人,我打算写一篇文章,目标是只需简单复制粘贴就能让它动起来。我主要参考了基本的构建RESTful Web服务的教程。

这篇文章的源代码

如果按照本文执行,可以得到一个可以运行的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"
$

只要有Maven,即使在Windows上也可以使用几乎相同的步骤来运行所谓的普通Mac。

接下来,我将使用curl进行通信。

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

试一试

首先,让我们从下面的位置复制并粘贴 pom.xml文件来创建它。

$ mkdir myproject && cd $_
$ cat 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>

创建一个目录来放置源代码和属性文件。

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

创建一个写有启动Spring Boot的咒语的文件。

$ cat src/main/java/nu/mine/kino/springboot/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);
	}

}

我们将创建一个下面的Controller来描述WEB功能。

$ cat src/main/java/nu/mine/kino/springboot/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
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。
辛苦了。

赠品

转化为罐头

$ mvn clean package

所以,可以生成一个包含Tomcat的可执行的jar文件。

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

通过执行以上操作,Tomcat会像之前的mvn spring-boot:run命令一样启动。

使用Eclipse导入

$ mvn eclipse:clean eclipse:eclipse

当您完成项目文件(.project/.classpath),就可以将它们导入Eclipse中。

将返回的JSON数据进行格式化并返回

将以下配置添加到application.properties文件中。

$ cat src/main/resources/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已经被格式化了。

相关链接

Spring Boot 公式
Building a RESTful Web Service
Developing Your First Spring Boot Application

Appendix A. Common application properties application.properties の設定可能な項目一覧。

https://github.com/masatomix/spring-boot-sample-tomcat この記事のソースコード

广告
将在 10 秒后关闭
bannerAds