SpringBoot集成Swagger
一、pom.xml中引入如下依賴:
<!-- swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!--swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
二、編輯resource/application.yml文件,添加如下配置:
spring:
mvc:
pathmatch:
matching-strategy: ant_path_matcher
三、SwaggerConfig配置類的編寫
/** * @project * @Description * @Author songwp * @Date 2022/8/19 16:01 * @Version 1.0.0 **/ @Configuration //配置類 @EnableSwagger2 //開啟swagger2的自動(dòng)配置 public class SwaggerConfig { private static final String TOKEN_HERDER_KEY = "token"; /** * swagger文檔配置 */ @Bean public Docket customDocket() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.songwp.controller")) .paths(PathSelectors.any()) .build() .globalOperationParameters(this.getParameterList());// 全局配置 } /** * 添加head參數(shù)配置 */ private List<Parameter> getParameterList() { ParameterBuilder clientIdTicket = new ParameterBuilder(); List<Parameter> pars = new ArrayList<Parameter>(); clientIdTicket.name(TOKEN_HERDER_KEY).description("token令牌") .modelRef(new ModelRef("string")) .parameterType("header") .required(false).build(); //設(shè)置false,表示clientId參數(shù) 非必填,可傳可不傳! pars.add(clientIdTicket.build()); return pars; } /** * api相關(guān)配置 */ private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("swagger 接口文檔") .contact(new Contact("songwp", "http://localhost:8080/swagger-ui.html", "")) .description("swagger-bootstrap-ui") .termsOfServiceUrl("http://localhost:8080/swagger-ui.html") .version("1.0") .build(); }
四、Swagger常用注解:
//在Controller層的應(yīng)用: //1.在類上應(yīng)用的注解: @Api(tags = "這是一個(gè)控制器類") //2.在具體請求方法上的注解: @ApiOperation(value = "功能總述" , notes = "具體描述") @ApiParam(value = "請求參數(shù)說明") //在POJO層的應(yīng)用: //1.在類上應(yīng)用的注解: @ApiModel(description = "XX實(shí)體類") //2.在實(shí)體類屬性上應(yīng)用的注解: @ApiModelProperty(value = "屬性說明")
五、訪問Swagger-UI
Swagger版本為2.9.2: 直接訪問:localhost:8080/swagger-ui.html Swagger版本為3.0.0: 直接訪問:localhost:8080/swagger-ui/index.html
六、訪問如下圖:

古今成大事者,不唯有超世之才,必有堅(jiān)韌不拔之志!

浙公網(wǎng)安備 33010602011771號(hào)