构建一个 RESTful web service

  • 能够接收 HTTP GET 请求:
http://localhost:8080/greeting
  • 使用JSON作为响应,返回问候语句:
{"id":1,"content":"Hello, World!"}
  • 在URL的query string中可以使用自定义的name参数:
http://localhost:8080/greeting?name=User
  • name参数替换默认值World,响应JSON如下:
{"id":1,"content":"Hello, User!"}

配置pom的parent:

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

spring-boot-starter-parent features:

  • 默认编译级别为Java 1.6
  • 编码格式为UTF-8
  • Dependency Management,忽略<version>标签,继承自spring-boot-denepdencies
  • Sensible resource filtering
  • Sensible plugin configuration
  • Sensible resource filtering for application.properties and application.yml

添加spring-boot-maven-plugin:

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

Spring Boot Maven Plugin features:

  1. 将classpath下的所有jar包打进一个可执行über-jar
  2. 搜索 public static void main()并把它标记为runnable classpath
  3. 设置默认依赖版本号

创建Greeting POJO类

package com.example;

public 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;
	}

}

Spring使用Jackson JSON将POJO类转换为JSON

创建Controller

package com.example;

import java.util.concurrent.atomic.AtomicLong;

import org.springframework.web.bind.annotation.RequestMapping大专栏  Spring Guides: Building a RESTful Web Servicelass="o">;
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));
	}
}
  • @RestController: shorthand for @Controller and @ResponseBody rolled together Reference
  • MappingJackson2HttpMessageConverter: 自动将Greeting实例转换为JSON(Jackson 2 在classpath中)Reference

可执行程序

package com.example;

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

@SpringBootApplication
public class Application {

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}
}
  • @SpringBootApplication: @Configuration + @EnableAutoConfiguration + @ComponentScan

  • mvn spring-boot:run

Code Demo

Spring Guides References

02-01 15:04