> 文章列表 > springboot整合knife4j接口文档成公共模块使用

springboot整合knife4j接口文档成公共模块使用

springboot整合knife4j接口文档成公共模块使用


theme: smartblue

之前项目中一直用的是swagger-ui进行接口文档的调用和使用,最近前端一直反馈页面不美观,调用凌乱,等一系列问题。基于这个问题我决定将其进行更改调整,上网搜索了一下发现knife4j是目前接口文档不错的一款插件。打算将其替换swagger。

一、替换后的成果

1.替换前的:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-8xQNn7kU-1681872792230)(https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/5e6b4ed10d834df8a40b266be1ad754c~tplv-k3u1fbpfcp-watermark.image?)]

2. 替换后的:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Ens6k7i4-1681872792231)(https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/b252607b7a8244c0a984f85c604d954b~tplv-k3u1fbpfcp-watermark.image?)]

是不是清晰多了😁

二、导入knife4j的依赖

  1. 首先将原来swagger中的依赖注释或者去掉 如下:
<dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger2</artifactId><version>${swagger.fox.version}</version>
</dependency>

2.引入knife4j依赖(这个knife4j如果我们使用的jdk是java8的话,基本版本是3的就够用)

<dependency><groupId>com.github.xiaoymin</groupId><artifactId>knife4j-spring-boot-starter</artifactId><version>3.0.2</version>
</dependency>
<dependency><groupId>io.springfox</groupId><artifactId>springfox-boot-starter</artifactId><version>3.0.0</version>
</dependency>

三、代码配置

3.1实体代码配置-接收knife4j路径配置和swagger一样

@Data
@Component
@ConfigurationProperties("swagger")
public class SwaggerProperties
{/* 是否开启swagger*/private Boolean enabled;/* swagger会解析的包路径/private String basePackage = "";/* swagger会解析的url规则/private List<String> basePath = new ArrayList<>();/* 在basePath基础上需要排除的url规则/private List<String> excludePath = new ArrayList<>();/* 标题/private String title = "";/* 描述/private String description = "";/* 版本/private String version = "";/* 许可证/private String license = "";/* 许可证URL/private String licenseUrl = "";/* 服务条款URL/private String termsOfServiceUrl = "";/* host信息/private String host = "";/* 联系人信息*/private Contact contact = new Contact();/* 全局统一鉴权配置/private Authorization authorization = new Authorization();}

3.2 使用到EnableSwagger2注解,开启knife4j

@Configuration
@EnableSwagger2
@EnableAutoConfiguration
@ConditionalOnProperty(name = "swagger.enabled", matchIfMissing = true)
public class SwaggerAutoConfiguration
{/* 默认的排除路径,排除Spring Boot默认的错误处理路径和端点*/private static final List<String> DEFAULT_EXCLUDE_PATH = Arrays.asList("/error", "/actuator/");private static final String BASE_PATH = "/";@Bean@ConditionalOnMissingBeanpublic SwaggerProperties swaggerProperties(){return new SwaggerProperties();}@Beanpublic Docket api(SwaggerProperties swaggerProperties){// base-path处理if (swaggerProperties.getBasePath().isEmpty()){swaggerProperties.getBasePath().add(BASE_PATH);}// noinspection uncheckedList<Predicate<String>> basePath = new ArrayList<Predicate<String>>();swaggerProperties.getBasePath().forEach(path -> basePath.add(PathSelectors.ant(path)));// exclude-path处理if (swaggerProperties.getExcludePath().isEmpty()){swaggerProperties.getExcludePath().addAll(DEFAULT_EXCLUDE_PATH);}List<Predicate<String>> excludePath = new ArrayList<>();swaggerProperties.getExcludePath().forEach(path -> excludePath.add(PathSelectors.ant(path)));ApiSelectorBuilder builder = new Docket(DocumentationType.SWAGGER_2).host(swaggerProperties.getHost()).apiInfo(apiInfo(swaggerProperties)).select().apis(RequestHandlerSelectors.basePackage(swaggerProperties.getBasePackage()));swaggerProperties.getBasePath().forEach(p -> builder.paths(PathSelectors.ant(p)));swaggerProperties.getExcludePath().forEach(p -> builder.paths(PathSelectors.ant(p).negate()));return builder.build();}private ApiInfo apiInfo(SwaggerProperties swaggerProperties){return new ApiInfoBuilder().title(swaggerProperties.getTitle()).description(swaggerProperties.getDescription()).license(swaggerProperties.getLicense()).licenseUrl(swaggerProperties.getLicenseUrl()).termsOfServiceUrl(swaggerProperties.getTermsOfServiceUrl()).contact(new Contact(swaggerProperties.getContact().getName(), swaggerProperties.getContact().getUrl(), swaggerProperties.getContact().getEmail())).version(swaggerProperties.getVersion()).build();}
}

3.3 路径地址的配置

这样页面访问就可以:http:ip:端口/doc.html进行访问了

@Configuration
public class SwaggerWebConfiguration implements WebMvcConfigurer
{@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry){registry.addResourceHandler("/").addResourceLocations("classpath:/static/");registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");registry.addResourceHandler("/webjars/").addResourceLocations("classpath:/META-INF/resources/webjars/");}
}

3.5 重点:切记spring.factories中进行配置SwaggerAutoConfiguration和SwaggerWebConfiguration

大家可以自定义一个注解,这样其他模块就可以直接用swagger了,不需要每个模块都配置,下面是我的一个配置

@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import({ SwaggerAutoConfiguration.class })
public @interface EnableCustomSwagger2
{}

其他模块直接将swagger这个公共依赖引入,可以直接开启swagger使用了,界面如文章开头替换后swagger后的界面,大家可以参考!