springboot学习-整合 Swagger2

springboot学习-整合 Swagger2

  • 今天玩斗地主太专注了。导致我出现了幻听,满脑子都环绕着斗地主的背景音乐
  • 睡不着,写点代码。今年受疫情影响,开学晚,答辩早,毕业设计还没开始,最近在家想了想技术的问题,有很多选择的余地,但是设计的任务量太大,要重复很多次造轮子工程,时间有限。
  • 虽然问题很多,但依旧不会影响我学习的激情。

Swagger2是神马???

简单描述

  • 现在步入正题,讲一下今天学习的东西。
  • Swagger 是RESTFUL接口的文档在线自动生成工具。
  • Swagger官网
  • 作用:接口的文档在线自动生成和功能测试

常用注解

  • Rest风格用户的接口
  • Swagger2 注解整理

  • Api:修饰整个类,描述Controller的作用
  • ApiOperation:描述一个类的一个方法,或者说一个接口
  • ApiParam:单个参数描述
  • ApiModel:用对象来接收参数
  • ApiProperty:用对象接收参数时,描述对象的一个字段
  • ApiResponse:HTTP响应其中1个描述
  • ApiResponses:HTTP响应整体描述
  • ApiIgnore:使用该注解忽略这个API
  • ApiError :发生错误返回的信息
  • ApiImplicitParam:一个请求参数
  • ApiImplicitParams:多个请求参数

Swagger2的使用

引入依赖

		<dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-aopartifactId>
            <version>2.1.3.RELEASEversion>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-configuration-processorartifactId>
            <version>2.1.3.RELEASEversion>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-context-supportartifactId>
            <version>5.1.5.RELEASEversion>
        dependency>
        <dependency>
            <groupId>joda-timegroupId>
            <artifactId>joda-timeartifactId>
            <version>2.9.9version>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>fastjsonartifactId>
            <version>1.2.47version>
        dependency>
        
        <dependency>
            <groupId>io.springfoxgroupId>
            <artifactId>springfox-swagger2artifactId>
            <version>2.6.1version>
        dependency>
        <dependency>
            <groupId>io.springfoxgroupId>
            <artifactId>springfox-swagger-uiartifactId>
            <version>2.6.1version>
        dependency>

配置SwaggerConfig类

@Configuration
public class SwaggerConfig {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("top.runok"))//包名
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("笨蛋李冬虎的项目")
                .description("使用RestFul风格,利用Swagger构建API文档")
                .termsOfServiceUrl("#")
                .version("version 1.0")
                .build();
    }
}

使用开启注解 @EnableSwagger2

@EnableSwagger2
@SpringBootApplication
//在启动类加上注解
public class DemoApplication {

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

}

实现增删查改

@RestController
public class UserController {
    // 创建线程安全的Map
    static Map<Integer, User> users = Collections.synchronizedMap(new HashMap<Integer, User>());

    /**
     * 添加用户
     */
    @ApiOperation(value="添加用户", notes="创建新用户")
    @ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")
    @RequestMapping(value = "/addUser", method = RequestMethod.POST)
    public ResponseEntity<JsonResult> addUser (@RequestBody User user){
        JsonResult result = new JsonResult();
        try {
            users.put(user.getId(), user);
            result.setResult(user.getId());
            result.setStatus("ok");
        } catch (Exception e) {
            result.setResult("服务异常");
            result.setStatus("500");
            e.printStackTrace();
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 根据ID查询用户
     */
    @ApiOperation(value="用户查询", notes="根据ID查询用户")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Integer", paramType = "path")
    @RequestMapping(value = "/getUserById/{id}", method = RequestMethod.GET)
    public ResponseEntity<JsonResult> getUserById (@PathVariable(value = "id") Integer id){
        JsonResult result = new JsonResult();
        try {
            User user = users.get(id);
            result.setResult(user);
            result.setStatus("200");
        } catch (Exception e) {
            result.setResult("服务异常");
            result.setStatus("500");
            e.printStackTrace();
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 查询用户列表
     */
    @ApiOperation(value="用户列表", notes="查询用户列表")
    @RequestMapping(value = "/getUserList", method = RequestMethod.GET)
    public ResponseEntity<JsonResult> getUserList (){
        JsonResult result = new JsonResult();
        try {
            List<User> userList = new ArrayList<>(users.values());
            result.setResult(userList);
            result.setStatus("200");
        } catch (Exception e) {
            result.setResult("服务异常");
            result.setStatus("500");
            e.printStackTrace();
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 根据ID修改用户信息
     */
    @ApiOperation(value="更新用户", notes="根据Id更新用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long",paramType = "path"),
            @ApiImplicitParam(name = "user", value = "用户对象user", required = true, dataType = "User")
    })
    @RequestMapping(value = "/updateById/{id}", method = RequestMethod.PUT)
    public ResponseEntity<JsonResult> updateById (@PathVariable("id") Integer id, @RequestBody User user){
        JsonResult result = new JsonResult();
        try {
            User user1 = users.get(id);
            user1.setUsername(user.getUsername());
            user1.setAge(user.getAge());
            users.put(id, user1);
            result.setResult(user1);
            result.setStatus("ok");
        } catch (Exception e) {
            result.setResult("服务异常");
            result.setStatus("500");
            e.printStackTrace();
        }
        return ResponseEntity.ok(result);
    }

    /**
     * 根据id删除用户
     */
    @ApiOperation(value="删除用户", notes="根据id删除指定用户")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long", paramType = "path")
    @RequestMapping(value = "/deleteById/{id}", method = RequestMethod.DELETE)
    public ResponseEntity<JsonResult> deleteById (@PathVariable(value = "id") Integer id){
        JsonResult result = new JsonResult();
        try {
            users.remove(id);
            result.setResult(id);
            result.setStatus("ok");
        } catch (Exception e) {
            result.setResult("服务异常");
            result.setStatus("500");
            e.printStackTrace();
        }
        return ResponseEntity.ok(result);
    }

    @ApiIgnore//使用该注解忽略这个API
    @RequestMapping(value = "/ignoreApi", method = RequestMethod.GET)
    public String  ignoreApi() {
        return "Spring Boot Swagger !";
    }
}

  • 效果图
    springboot学习-整合 Swagger2_第1张图片
  • 武汉加油!!!
  • 我还有个公众号,好久没让人关注了,感兴趣的可以关注一下。
  • 下载地址
    springboot学习-整合 Swagger2_第2张图片

你可能感兴趣的:(web,springboot,java)