直接接入优化后的界面更美观、文档分类更清晰的版本。
1.在pom.xml中引入依赖:
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring</artifactId>
<version>1.9.6</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-ui</artifactId>
<version>1.9.6</version>
</dependency>
2.创建SwaggerProperties类,用于归类配置属性:
@ConfigurationProperties("spring.swagger")
@Data
public class SwaggerProperties {
@NotEmpty(message = "标题不能为空")
private String title;
@NotEmpty(message = "描述不能为空")
private String description;
@NotEmpty(message = "作者不能为空")
private String author;
@NotEmpty(message = "版本不能为空")
private String version;
@NotEmpty(message = "扫描的 package 不能为空")
private String basePackage;
}
3.创建SwaggerConfiguration类:
@AutoConfiguration
@EnableSwagger2
public class SwaggerConfiguration {
@Bean
public Docket createRestApi(SwaggerProperties properties) {
return new Docket(DocumentationType.SWAGGER_2)
// ① 用来创建该 API 的基本信息,展示在文档的页面中(自定义展示的信息)
.apiInfo(apiInfo(properties))
// ② controller路径
.select()
.apis(basePackage(properties.getBasePackage()))
.paths(PathSelectors.any())
.build()
}
/**
* API 摘要信息
*/
private static ApiInfo apiInfo(SwaggerProperties properties) {
return new ApiInfoBuilder()
.title(properties.getTitle())
.description(properties.getDescription())
.contact(new Contact(properties.getAuthor(), null, null))
.version(properties.getVersion())
.build();
}
}
4.启动应用:访问地址为:http://127.0.0.1:应用端口号/doc.html