Swagger2的基本使用

第一步:導入核心包

<!--swagger-->
<dependency>
     <groupId>io.springfox</groupId>
     <artifactId>springfox-swagger2</artifactId>
     <scope>provided </scope>
 </dependency>
 <dependency>
     <groupId>io.springfox</groupId>
     <artifactId>springfox-swagger-ui</artifactId>
     <scope>provided </scope>
 </dependency>

第二步:創建配置文件

import com.google.common.base.Predicates;
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.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 //swagger註解
public class SwaggerConfig {

    @Bean
    public Docket webApiConfig(){
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("webApi")
                .apiInfo(webApiInfo())
                .select()
                .paths(Predicates.not(PathSelectors.regex("/admin/.*")))
                .paths(Predicates.not(PathSelectors.regex("/error.*")))
                .build();

    }

    private ApiInfo webApiInfo(){

        return new ApiInfoBuilder()
                .title("網站-課程中心API文檔")
                .description("本文檔描述了課程中心微服務接口定義")
                .version("1.0")
                .contact(new Contact("java", "http://xcm.com", "[email protected]"))
                .build();
    }
}

第三步:編寫測試接口

/**
 * <p>
 * 講師 前端控制器
 * </p>
 *
 * @author testjava
 * @since 2020-06-15
 */
@Api(description = "講師管理")
@RestController
@RequestMapping("/eduservice/teacher")
public class EduTeacherController {

    // 注入service
    @Autowired
    private EduTeacherService teacherService;


    // 查詢所有講師數據
    @ApiOperation(value = "所有講師列表")
    @GetMapping("findAll")
    public List<EduTeacher> findAllTeacher(){
        List<EduTeacher> list = teacherService.list(null);
        return list;
    }


    // 邏輯刪除講師
    @ApiOperation(value = "邏輯刪除講師")
    @DeleteMapping("{id}")
    public boolean removeTeacher(@ApiParam(name = "id", value = "講師ID", required = true) @PathVariable String id){
        boolean flag = teacherService.removeById(id);
        return flag;
    }

}

第四步:測試接口

訪問:http://localhost:8001/swagger-ui.html

細節注意:

1、如果有分包的情況或者配置類不在啓動類所在的子目錄下,要添加這個
@ComponentScan(basePackages = {“com.xcm”})
註解,不然掃描不到這個配置類
2、Swagger的作用本質上和postman差不多,都是測試接口用的
3、這三個都是Swagger的註解類,作用是用於功能提示,提高接口文檔的可視化
@Api(description = “講師管理”)
@ApiOperation(value = “所有講師列表”)
@ApiParam(name = “id”, value = “講師ID”, required = true)
分別作用在類、方法、參數上

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章