Spring Boot - 构建RESTful API

Spring Boot构建RESTful API极为简单,实际就是Spring MVC!

1.Spring MVC实现RESTful API

直接给出controller层代码:UserController.java

简单起见,controller层直接返回结果

package com.example.springboot.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.springboot.model.User;
import org.springframework.web.bind.annotation.*;

@SuppressWarnings("unused")
@RestController
@RequestMapping(value = "/users")
public class UserController {

    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    public String queryUser(@PathVariable Long id){
        return "query user:"+id;
    }

    @RequestMapping(value = "/",method = RequestMethod.GET)
    public String queryUsers(){
        return "query all users";
    }

    @RequestMapping(value = "/",method = RequestMethod.POST)
    public String addUser(@RequestBody User user){
        return "add user:"+ JSONObject.toJSONString(user);
    }

    @RequestMapping(value = "/{id}",method = RequestMethod.PUT)
    public String updateUser(@PathVariable Long id,@RequestBody User user){
        return "update user,id:"+id+",user:"+JSONObject.toJSONString(user);
    }

    @RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
    public String deleteUser(@PathVariable Long id){
        return "delete user,id:"+id;
    }
}

特别注意:
POSTPUT方法中,使用@RequestBody时,仅支持content-type:application/json;使用@ModelAttribute时,仅支持content-type:application/x-www-form-urlencoded(已亲测,至于为什么请细看相关注解的具体实现)

2.API文档支持:Swagger2

Swagger2可以利用注解快速、自动地生成接口文档页面,方便调用方查阅!

Step 1:添加Swagger2相关依赖springfox-swagger2springfox-swagger-ui

dependencies {
    compile group: 'com.alibaba', name: 'fastjson', version: '1.2.38'
    compile('org.springframework.boot:spring-boot-starter')
    compile('org.springframework.boot:spring-boot-starter-web')
    compile('org.springframework.boot:spring-boot-starter-thymeleaf')
    compile('io.springfox:springfox-swagger2:2.7.0')
    compile('io.springfox:springfox-swagger-ui:2.7.0')
    testCompile('org.springframework.boot:spring-boot-starter-test')
}

Step 2:在SpringbootApplication.java同路径下创建Swagger2.java

package com.example.springboot;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class Swagger2 {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.springboot.controller"))//controller所在包名
                .paths(PathSelectors.any())
                .build();
    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("这是标题")
                .description("这是说明")
                .termsOfServiceUrl("服务地址")
                .contact(new Contact("你的名字","你的网址","你的email"))
                .version("1.0")
                .build();
    }
}

Step 3:在Controller层代码中加入Swagger2相关注解
@ApiOperation:简单描述
@ApiImplicitParams:多个参数
@ApiImplicitParam:单个参数

package com.example.springboot.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.springboot.model.User;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

@SuppressWarnings("unused")
@RestController
@RequestMapping(value = "/users")
public class UserController {

    @ApiOperation(value = "查询单个用户",notes = "根据id查询单个用户")
    @RequestMapping(value = "/{id}",method = RequestMethod.GET)
    @ApiImplicitParam(name = "id",value = "用户id",required = true)
    public String queryUser(@PathVariable Long id){
        return "query user:"+id;
    }

    @ApiOperation(value = "查询所有用户",notes = "查询所有用户")
    @RequestMapping(value = "/",method = RequestMethod.GET)
    public String queryUsers(){
        return "query all users";
    }

    @ApiOperation(value = "新增用户",notes = "新增用户")
    @RequestMapping(value = "/",method = RequestMethod.POST)
    public String addUser(@RequestBody User user){
        return "add user:"+ JSONObject.toJSONString(user);
    }

    @ApiOperation(value = "修改用户",notes = "修改用户")
    @RequestMapping(value = "/{id}",method = RequestMethod.PUT)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "用户id",required = true),
            @ApiImplicitParam(name = "user",value = "用户信息json",required = true)
    })
    public String updateUser(@PathVariable Long id,@RequestBody User user){
        return "update user,id:"+id+",user:"+JSONObject.toJSONString(user);
    }

    @ApiOperation(value = "删除用户",notes = "根据id删除用户")
    @RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
    public String deleteUser(@PathVariable Long id){
        return "delete user,id:"+id;
    }
}

Step 4:访问http://localhost:8080/swagger-ui.html页面查看API文档

Spring Boot - 构建RESTful API_第1张图片
swagger-ui.png

此页面中除了API接口说明外,还提供了每个接口的测试(“try it out”按钮可以发起请求),但@PathVariable类型的注解似乎不支持,所以这个页面还是仅供查阅吧,具体调用测试还是用专业点的rest工具(如postman、rested client等等)

你可能感兴趣的:(Spring Boot - 构建RESTful API)