springboot2.0使用swagger2生成接口文档
一、在pom中引入依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
<exclusions>
<exclusion>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--替换models模块,解决不声明example控制台报错问题-->
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
<version>1.6.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<!--第三方ui依赖-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.9.6</version>
</dependency>
二、写配置
@Configuration
@EnableSwagger2
@EnableSwaggerBootstrapUI
public class Swagger2 {
// http://localhost:port/contenxt-path/swagger-ui.html 原路径
// http://localhost:port/contenxt-path/doc.html 新ui路径
// 配置swagger2核心配置 docket
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2) // 指定api类型为swagger2
.apiInfo(apiInfo()) // 用于定义api文档汇总信息
.select()
.apis(RequestHandlerSelectors
.basePackage("net.xxx.web")) // 指定controller包
.paths(PathSelectors.any()) // 所有controller
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("测试api") // 文档页标题
.contact(new Contact("hxm",
"http://192.168.1.185:8091",
"xxx@.gmail.com")) // 联系人信息
.description("测试api") // 详细信息
.version("0.0.1") // 文档版本号
.termsOfServiceUrl("http://www.xxx.com") // 网站地址
.build();
}
}
三、映射静态资源
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
// 实现静态资源的映射
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/**")
.addResourceLocations("classpath:/META-INF/resources/"); // 映射swagger2
}
}
四、写一个controller
@ApiSort(value = 1)
@Api(value = "消息管理",tags = {"用于消息管理的相关接口"})
@RequestMapping("message")
@RestController
public class MessageController {
@Autowired
MessageService messageService;
/**
* 发布消息
* @param messageBO
* @return
*/
@ApiOperationSupport(order = 1)
@ApiOperation(value = "发布消息",notes = "发布消息notes",httpMethod = "POST")
@PostMapping("add")
@OperLog(operModul = "消息管理",operType = OperTypeEnum.ADD)
public ReturnData add(@RequestBody MessageBO messageBO){
ReturnData returnData = ReturnData.getSuccess();
messageService.add(messageBO);
return returnData;
}
}
五、有url拦截器的话将swagger资源放行
"/swagger-resources/**",
"/webjars/**",
"/v2/**",
"/swagger-ui.html/**",
"/configuration/**"
执行完以上步骤以后,可以访问swager文档地址,查看生成文档效果
常用注解
@Api(value = “消息管理”,tags = {“用于消息管理的”})
作用在controller类上
@ApiOperation(value = “发布消息”,notes = “发布消息notes”,httpMethod = “POST”)
作用在controller类里的一个方法,标注接口 依赖@Api
@ApiModel(value = “消息对象”,description = “从客户端,由用户传入的数据封装在此entity中”)
作用在model类上,入参和返回参数的声明
@ApiModelProperty(value = “标题”)
作用在model类的属性上,和@ApiModel一起使用
六、其它
当入参是map时,参照以下连接修改
map参数