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.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
            <version>2.1.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <version>2.1.3.RELEASE</version>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>5.1.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.9.9</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>
        <!-- Swagger2 核心依賴 -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.6.1</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.6.1</version>
        </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 !";
    }
}

  • 效果圖
    在這裏插入圖片描述
  • 武漢加油!!!
  • 我還有個公衆號,好久沒讓人關注了,感興趣的可以關注一下。
  • 下載地址
    在這裏插入圖片描述
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章