思路:
导入依赖jar包->开启swagger(注解)->配置swagger相关信息->启动测试
实现:
1、pom.xml引入依赖包
<!-- 6、 swagger 文档管理集成 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.0</version>
</dependency>
<!-- 7、 swagger 在线UI支持 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.0</version>
</dependency>
2、启动入口使用注解启用swagger
@SpringBootApplication
@EnableSwagger2 // swagger 1、启用 Springfox swagger 2
@MapperScan("club.isource.platform.dao.mapper")
public class App
{
public static void main( String[] args )
{
SpringApplication.run(App.class, args);
}
}
3、swagger配置类配置相关信息
新建SwaggerConfig.java文件
@Configuration
@ComponentScan(basePackages={"club.isource.platform"}) // swagger 2、在线文档api类所在包
public class SwaggerConfig {
此类可以直接在启动入口类直接写,但是为了易于管理,使用单独的配置类。
文档信息方法ApiInfo的实现
private ApiInfo apiInfo() {
@SuppressWarnings("rawtypes")
ApiInfo apiinfo = new ApiInfo(
"微服务架构在线接口文档", // 题目
"api接口文档说明,实现文档在线查看、运行和测试!", // 文档描述
"1.0", // 版本号
"urn:tos", // termsOfServiceUrl
// 联系方式
new Contact("gosenkle", // 姓名
"http://www.gaoxinguo.net", // url
"gaoxinguo@qq.com"), // email
"", // license
"", // license url
new ArrayList<VendorExtension>()); // 有非空判断,给一个非空值
return apiinfo;
}
配置类实现文档对象Docket示例
@Bean
public Docket platformApi() {
System.err.println("文档集装。。。");
return new Docket(DocumentationType.SWAGGER_2) // swagger 3、Docket Springfox的主要api配置装置,这里初始化为swagger规范2.0
.select() // swagger 4、 返回ApiSelectorBuilder实例 对暴露的端点进行细粒度的控制
.apis(RequestHandlerSelectors.any()) // swagger 5、使用断言确定请求处理的选择,这里使用一个any缺省断言
.paths(PathSelectors.any()) // swagger 6、使用断言确定路径的选择,这里使用缺省的any断言
.build() // swagger 7、 配置完apis和path后进行组建选择器
.apiInfo(apiInfo()) ;// swagger api 基本信息配置 }
测试
启动界面:http://127.0.0.1:8080/v1/swagger-ui.html
如图,可以看到虽然还未使用注解,控制层的user接口已经显示,只是没有格式化而已。