Spring Boot 配置 Knife4j

一、引入 maven

  
<dependency>  
    <groupId>com.github.xiaoymingroupId>  
    <artifactId>knife4j-openapi2-spring-boot-starterartifactId>  
    <version>4.1.0version>  
dependency>

二、配置 application.yml

knife4j:  
  # 开启增强配置  
  enable: true 
  setting:  
    # 是否启用 Host    
    enable-host: true  
    # 启用 Host 地址  
    enable-host-text: "http://yunhu.wiki/api"  
  # 配置账号密码访问文档  
  basic:  
    enable: true  
    username: admin  
    password: 123456

三、knife4j 配置类

import com.github.xiaoymin.knife4j.spring.extension.OpenApiExtensionResolver;  
import io.swagger.annotations.ApiOperation;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.context.annotation.Bean;  
import org.springframework.context.annotation.Configuration;  
import springfox.documentation.builders.ApiInfoBuilder;  
import springfox.documentation.builders.PathSelectors;  
import springfox.documentation.builders.RequestHandlerSelectors;  
import springfox.documentation.service.ApiInfo;  
import springfox.documentation.spi.DocumentationType;  
import springfox.documentation.spring.web.plugins.Docket;  
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;  
  
/**  
 * 配置 Knife4j 接口文档  
 *  
 * @author: yunhu  
 * @date: 2023/7/30  
 */  
@Configuration  
@EnableSwagger2WebMvc  
public class Knife4jConfiguration {  
    private final OpenApiExtensionResolver openApiExtensionResolver;  
  
    @Autowired  
    public Knife4jConfiguration(OpenApiExtensionResolver openApiExtensionResolver) {  
        this.openApiExtensionResolver = openApiExtensionResolver;  
    }  
  
  
    @Bean(value = "defaultApi2")  
    public Docket defaultApi2() {  
        String groupName = "yunhu-library";  
        Docket docket = new Docket(DocumentationType.SWAGGER_2)  
                .apiInfo(apiInfo())  
                .groupName(groupName)  
                .select()  
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) 
                .paths(PathSelectors.any())  
                .build()  
                .extensions(openApiExtensionResolver.buildExtensions(groupName));  
        return docket;  
    }  
  
    private ApiInfo apiInfo() {  
        return new ApiInfoBuilder()  
                .description("# swagger-bootstrap-ui-demo RESTful APIs")  
                .termsOfServiceUrl("http://www.library.wiki")  
                .version("1.0")  
                .build();  
    }  
}

四、常用 api 注解

@Api(tags = "后台书籍管理模块") // 控制层类的注解,接口的分组名称

@ApiOperation("创建书籍") // 控制层类中的方法注解

@ApiModel(value = "BookEntity", description = "书籍实体类") // 实体类的注解

@ApiModelProperty(value = "书籍 id") // 字段的注解

五、参考资料

  • Knife4j 官方文档

你可能感兴趣的:(java,spring,boot)