1.前提
一定要看好版本。
Springboot ? Swagger各版本整理_swagger版本_qq_33334411的博客-CSDN博客
我的版本:
<dependency><groupId>io.springfox</groupId><artifactId>springfox-boot-starter</artifactId><version>3.0.0</version></dependency>
2. 使用
新建一個boot web項目之后,導入上述依賴。
在confi包下新建一個SwaggerConfig.java配置類
Swgger2Config.java
@Configuration
@EnableSwagger2 // 3.0版本加不加無所謂
public class Swagger2Config {@Beanpublic Docket coreApiConfig(){return new Docket(DocumentationType.SWAGGER_2).apiInfo(adminApiInfo()).groupName("group1").select().build();}private ApiInfo adminApiInfo(){return new ApiInfoBuilder().title("后臺管理系統--api文檔").description("后臺管理系統接口描述").version("1.0").contact(new Contact("郡主喵","http://baidu.com","728831102@qq.com")).build();}
}
在controller包新建HelloController.java
@RestController
@ResponseBody
@Api(tags = "你好相關接口:")
public class HelloController {@GetMapping("/hellow")@ApiOperation("這是一個測試接口")public HelloVO hello(){return new HelloVO("qhx",11);}
}
在modle.vo下新建HelloVO.java
@ApiModel(value = "HelloVO",description = "你好相關接口的信息封裝")
public class HelloVO {@ApiModelProperty("姓名")private String name;@ApiModelProperty("年齡")private Integer age;public String getName() {return name;}public Integer getAge() {return age;}public void setName(String name) {this.name = name;}public void setAge(Integer age) {this.age = age;}public HelloVO(String name, Integer age) {this.name = name;this.age = age;}
}
在application.yml/properties文件中添加
spring:mvc:pathmatch:matching-strategy: ant_path_matcher
運行,訪問?http://localhost:8081/swagger-ui/index.html
?看到如上,及成功。
一般常用的swagger2注解:
@Api:修飾整個類,描述Controller的作用
@ApiOperation:描述一個類的一個方法,或者說一個接口
@ApiParam:單個參數描述
@ApiModel:用對象來接收參數
@ApiModelProperty:用對象接收參數時,描述對象的一個字段
@ApiImplicitParam:一個請求參數 @ApiImplicitParams:多個請求參數
3.報錯解決
1.Unable to start web server; nested exception is org.springframework.context.ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean.
忘加這個。
?2.?Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException
SpringBoot2.6.x使用PathPatternMatcher匹配路徑,Swagger引用的Springfox基于AntPathMatcher匹配路徑。匹配方式不同,導致錯誤。
因此在application.yaml/properties 文件新加。
spring:mvc:pathmatch:matching-strategy: ant_path_matcher
3.訪問頁面為空
你項目中加了攔截器,需要在攔截器相應的放行靜態資源。
springboot集成swagger頁面空白解決方法_swagger 空白_立碼收復惡眛里懇的博客-CSDN博客