引言
使用springboot整合swagger是遇到一个坑,使用swagger的版本为3.0是访问ui页面报404不知道怎么半,反正没整明白,就把版本换为2.9的就好了,但是看swagger的文件结构发现里面没有那个swagger-ui.html页面了也难怪找不到,本人能力有限不会解决404问题,只能换成2.9版本的swagger,正常访问页面
本文很多是在网上其他资源上找的仅供学习使用和参考
第一步 添加依赖
注意这里的版本号为2.9,前面试过3.0失败了显示不了ui.html这个页面,反正没整明白,换为2.9就好了
<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>
第二步 新建配置类
在config包下新建swaggerConfig.class
package com.cheng.cms.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
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;
import java.util.ArrayList;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//为当前包路径
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
//作者信息
Contact contact = new Contact("cheng_nge", "自己的链接地址", "邮箱");
return new ApiInfo(
"xx的SwaggerAPI文档",
"潇洒而勇敢~",
"v1.0",
"自己的链接地址",
contact,
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList()
);
}
}
第三步 添加swagger注解
在类上添加类说明
在方法上添加方法说明
在参数上添加参数说明等等
例:在controller里添加一些注解
@Controller
@Api("用户管理API")
public class ResidentController {
@Autowired
private ResidentService residentService;
@ApiOperation("跳转到用户信息页面")
@GetMapping("/queryInfo/residentInfo")
public String residentInfo(ModelMap modelMap){
List<Residents> residents = residentService.selectAllResidents();
modelMap.put("residentInfo",residents);
return "queryInfo/residentInfo";
}
}
第四步 访问
ui页面
http://localhost:8080/swagger-ui.html
### 文档
```java
http://localhost:8080/v2/api-docs
第五步 其他说明
Swagger注解 简单说明
@Api(tags = “xxx模块说明”) 作用在模块类上
@ApiOperation(“xxx接口说明”) 作用在接口方法上
@ApiModel(“xxxPOJO说明”) 作用在模型类上:如VO、BO
@ApiModelProperty(value = “xxx属性说明”,hidden = true) 作用在类方法和属性上,hidden设置为true可以隐藏该属性
@ApiParam(“xxx参数说明”) 作用在参数
方法和字段上,类似@ApiModelProperty