Java Spring 入门

10.8'21

介绍

Why Spring?

Spring makes programming Java quicker, easier, and safter for everybody. Spring's focus on speed, simplicity, and productivity has made it the world's most popular java framework.

Spring 用于快速有效地构建应用。是一套项目基础模板和工具。

  • Spring Boot 是一个快速启动 Spring、打包第三方库、减少配置的基础框架。

Quickstart Guide

创建新的 Spring Boot 项目

使用 Spring Initializr | https://start.spring.io 图形界面设置和创建项目。

添加依赖Spring Web, 点击Generate按钮,下载并解压 zip 文件。

添加代码

添加路由/helllo,处理参数和返回值

src/main/java/com/example/demo/DemoApplication.java

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class DemoApplication {

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

    @GetMapping("/hello")
    public String hello(@RequestParam(value="name", defaultValue="World") String name) {
        return String.format("Hello %s", name);
    }
}

启动项目

项目下运行命令

./mvnw spring-boot:run

打开网页localhost:8080/hello?name=User,可以看到相应结果。

Spring Boot Devtools

使用 devtools,当修改文件后重新 compile,自动重启项目

添加有依赖到 pom.xml

<dependencies>
  <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-devtools</artifactId>
      <optional>true</optional>
  </dependency>
</dependencies>

运行命令

./mvnw spring-boot:run

修改 src 下的 java 文件

新的终端中运行命令

./mvnw compile

inotifywait

可以检测文件变化实现自动 compile 和 restart

Ubuntu 为例

sudo apt install inotify-tools

dev.sh

#!/bin/bash

monitor() {
inotifywait -m -e create -e modify -e delete -e delete_self -e move $1 |
  while read path action file; do
    if [[ "$file" =~ .*java$ ]]; then
      ./mvnw compile
    fi
  done
}

monitor  "./src/main/java/com/example/demo" &

./mvnw spring-boot:run

fswatch

https://github.com/emcrisostomo/fswatch

sudo apt install fswatch
#!/bin/bash

monitor() {
  fswatch -0 $1 | while read -d "" event;
    do
      ./mvnw compile
    done
}

monitor  "./src/main" &

./mvnw spring-boot:run

RESTful Web Service

目标

创建服务,访问http://localhost:8080/greeting返回 JSON 数据

{"id": 1, "content": "Hello, World!"}

访问http://localhost:8080/greeting?name=User返回 JSON 数据

{"id": 1, "content": "Hello, User!"}

依赖

创建新的 Spring Boot 项目

使用 Spring Initializr | https://start.spring.io 图形界面设置和创建项目。

添加依赖Spring Web, 点击Generate按钮,下载并解压 zip 文件。

添加代码

添加数据结构模型

src/main/java/com/example/demo/Greeting.java

package com.example.demo;

public class Greeting {
    private String name;

    public Greeting(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

添加 Controller 来处理请求

src/main/java/com/example/demo/GreetingController.java

package com.example.demo;

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

@RestController
public class GreetingController {

    @GetMapping("/greeting")
    public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
        return new Greeting(name);
    }
}

启动项目

项目下运行命令

./mvnw spring-boot:run

打开网页localhost:8080/greeting,可以看到相应结果。

打包后运行

./mvnw clean package
java -jar target/demo-0.0.1-SNAPSHOT.jar

返回数组例子

package com.example.demo;

import java.util.concurrent.atomic.AtomicLong;
import java.util.List;
import java.util.ArrayList;

import org.springframework.web.bind.annotation.GetMapping;
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();

  @GetMapping("/greetings")
  public List<Greeting> greetings(@RequestParam(value="name", defaultValue="World") String name) {
    List<Greeting> greetings = new ArrayList<Greeting>();
    greetings.add(new Greeting(counter.incrementAndGet(), String.format(template, name)));
    greetings.add(new Greeting(counter.incrementAndGet(), String.format(template, name)));

    return greetings;
  }
}

Serving Web Content with Spring MVC

📖