Swagger的使用

本文介绍了如何在SpringBoot项目中使用Maven坐标引入knife4j插件,配置Swagger_2生成接口文档,并定制化资源映射和自定义拦截器。同时,展示了Swagger2中常用的注解对API进行文档化的用法。
摘要由CSDN通过智能技术生成

一、引入Maven坐标

<dependency>
	<groupld>com.github.xiaoymin</groupld>
	<artifactld>knife4j-spring-boot-starter</artifactld>
	<version>3.0.2</version>
</dependency>

二、配置类中添加配置

  • 根据自己的项目实际情况配置
/**
     * 通过knife4j生成接口文档
     * @return
     */
    @Bean
    public Docket docket() {
        ApiInfo apiInfo = new ApiInfoBuilder()
                .title("苍穹外卖项目接口文档")
                .version("2.0")
                .description("苍穹外卖项目接口文档")
                .build();
        Docket docket = new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.sky.controller")) //此处注意,包路径一定不要配错,根据自己的web层包来
                .paths(PathSelectors.any())
                .build();
        return docket;
    }

三、配置类继承WebMvcConfigurationSupport类重写addResourceHandlers()方法完成资源映射

/**
     * 设置静态资源映射
     * @param registry
     */
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
    //将doc.html文件映射(存放)到resources目录下
        registry.addResourceHandler("/doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

完整代码示例:

@Configuration
@Slf4j
public class WebMvcConfiguration extends WebMvcConfigurationSupport {

    @Autowired
    private JwtTokenAdminInterceptor jwtTokenAdminInterceptor;

    /**
     * 注册自定义拦截器
     *
     * @param registry
     */
    protected void addInterceptors(InterceptorRegistry registry) {
        log.info("开始注册自定义拦截器...");
        registry.addInterceptor(jwtTokenAdminInterceptor)
                .addPathPatterns("/admin/**")
                .excludePathPatterns("/admin/employee/login");
    }

    /**
     * 通过knife4j生成接口文档
     * @return
     */
    @Bean
    public Docket docket() {
        ApiInfo apiInfo = new ApiInfoBuilder()
                .title("苍穹外卖项目接口文档")
                .version("2.0")
                .description("苍穹外卖项目接口文档")
                .build();
        Docket docket = new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.sky.controller"))
                .paths(PathSelectors.any())
                .build();
        return docket;
    }

    /**
     * 设置静态资源映射
     * @param registry
     */
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/doc.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}

常用注解

在Swagger 2中,有几个核心的注解用于对RESTful API进行文档化和交互式测试。以下是 Swagger 2 常用的一些注解:

  • @Api
    作用:应用于控制器类上,表示这个类是一个API资源。
    示例:
     @Api(value = "Banner管理", description = "主页轮播图管理接口")
     @RestController
     @RequestMapping("/api/banner")
     public class BannerController {
         // ...
     }
     
  • @ApiOperation
    作用:应用于控制器类中的方法上,描述一个HTTP请求的操作(如GET、POST等)及其功能。
    属性:value(方法的简短描述)、notes(更详细的说明或备注信息)、httpMethod(请求类型,默认根据@RequestMapping确定)、response(响应体的引用,如果使用了@ApiResponses则不需要)等。
    示例:
     @ApiOperation(value = "获取指定ID的轮播图", notes = "通过ID获取详细轮播图信息")
     @GetMapping("/{id}")
     public ResponseEntity<Banner> getBanner(@PathVariable Long id) {
         // ...
     }
     
  • @ApiParam
    作用:应用于方法参数、方法返回值或实体类字段上,为参数提供元数据,包括名称、描述、是否必填等。
    属性:name(参数名)、value(参数说明文字)、required(是否必须提供该参数,默认false)、dataType(数据类型,默认自动推断)、defaultValue(默认值)等。
    示例:
     @GetMapping
     @ApiOperation("搜索轮播图")
     public ResponseEntity<List<Banner>> searchBanners(
         @ApiParam(name = "keyword", value = "搜索关键词", required = true)
         @RequestParam String keyword) {
         // ...
     }
     
  • @ApiModel
    作用:应用于实体类上,用于描述整个模型的信息,通常与@ApiModelProperty配合使用。
    属性:value(模型名称),description(模型的描述信息)。
  • @ApiModelProperty
    作用:应用于实体类的属性上,用于详细描述模型属性的信息。
    属性:同@ApiParam类似,包括name、value、required 等。
    示例:
     @ApiModel(value = "轮播图实体", description = "轮播图的基本信息")
     public class Banner {
         @ApiModelProperty(value = "主键ID", required = true)
         private Long id;
         
         // 其他字段和getter/setter...
     }
     

访问:项目启动路径:端口/doc.html

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值