Spring学习——Building a RESTful Web Service

网址: Building a RESTful Web Service

目标:使用Spring创建 “Hello, World” RESTful web服务

步骤
Step 1
使用Spring Initializr创建应用
initializr.png
build.gradle修改依赖
implementation 'org.springframework.boot:spring-boot-starter-web'

Step 2
Model 模型

package com.example.restservice;

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

Step 3
Controller 控制器

package com.example.restservice;

import java.util.concurrent.atomic.AtomicLong;

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("/greeting")
	public Greeting greeting(@RequestParam(value = "name", defaultValue = "World") String name) {
		return new Greeting(counter.incrementAndGet(), String.format(template, name));
	}
}

解析
@RestController标记该类为控制器,并且该类的每个方法都返回domain对象而不是视图。
@GetMapping确保HTTP GET请求/greeting映射到greeting()方法。
@RequestParam绑定name查询字符串参数到greeting()方法的name参数,如果请求中name值为空,就使用默认值(defaultValue)——“World”。
因为Spring的HTTP消息转换器,Greeting对象将自动转义成JSON。

Step 4
Main

package com.example.restservice;

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

@SpringBootApplication
public class RestServiceApplication {

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

}

解析
@SpringBootApplication是一个很方便的标签,它添加了一下所有内容:

  1. @Configuration将该类标记为应用程序上下文的Bean
  2. @EnableAutoConfiguration告诉Spring Boot根据添加的jar依赖猜测你想如何配置Spring
  3. @ComponentScan定义扫描的路径从中找出标识了需要装配的类自动装配到spring的bean容器中

Step 5
运行

  1. ./gradlew bootRun
  2. 生成JAR文件:./gradlew buildjava -jar build/libs/×××.jar

Step 6
测试
http://localhost:8080/greeting ⇒ {“id”:1,“content”:“Hello, World!”}
http://localhost:8080/greeting?name=User ⇒ {“id”:2,“content”:“Hello, User!”}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值