Swagger

Swagger

使用 Swagger你只需奥按照他的规范去定义接口及接口相关的信息,就可以做到生成接口文档,以及在线接口调试页面

官网:https://swagger.io/open in new window

Knife4jjava MVC框架集成 Swagger 生成api文档的增强解决方案

使用方式

导入坐标


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

在配置类中做配置

/**
 * 配置类,注册web层相关组件
 */
@Configuration
@Slf4j
public class WebMvcConfiguration extends WebMvcConfigurationSupport {
    /**
     * 通过knife4j生成接口文档
     * 接口分组
     * @return
     */
    @Bean
    public Docket docketAdmin() {
        log.info("准备生成接口文档");
        ApiInfo apiInfo = new ApiInfoBuilder()
                .title("苍穹外卖项目管理端接口文档")
                .version("2.0")
                .description("苍穹外卖项目接口文档")
                .build();
        Docket docketAdmin = new Docket(DocumentationType.SWAGGER_2)
                .groupName("管理端接口")
                .apiInfo(apiInfo)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.sky.controller.admin"))
                .paths(PathSelectors.any())
                .build();
        return docketAdmin;
    }

    @Bean
    public Docket docketUser() {
        log.info("准备生成用户端接口文档");
        ApiInfo apiInfo = new ApiInfoBuilder()
                .title("苍穹外卖项目用户端接口文档")
                .version("2.0")
                .description("苍穹外卖项目接口文档")
                .build();
        Docket docketUser = new Docket(DocumentationType.SWAGGER_2)
                .groupName("用户端接口")
                .apiInfo(apiInfo)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.sky.controller.user"))
                .paths(PathSelectors.any())
                .build();
        return docketUser;
    }

    /**
     * 设置静态资源映射
     * @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/");
    }
}

常用注解

通过注解可以控制生成的接口文档,使接口文档拥有更好的可读性,常用注解如下

注解作用
@Api用在类上,用来修饰整个类,例如controller,表示对类的说明
@ApiModel用在实体类上,例如entieyDTOVO
@ApiOperation用在方法上,表示对方法进行描述,例如接口名称,描述,版本等等
@ApiImplicitParam用在@ApiImplicitParams注解中,指定一个请求参数的各个方面
@ApiModelProperty用在属性上,描述属性信息
/**
 * 员工管理
 */
@RestController
@RequestMapping("/admin/employee")
@Slf4j
@Api(tags = "员工相关接口")//作用在类上,表示对类的说明
public class EmployeeController {
    @ApiOperation("员工登录接口")//作用在方法上,表示对方法进行描述
    @PostMapping("/login")
    public Result<EmployeeLoginVO> login(@RequestBody EmployeeLoginDTO employeeLoginDTO) {
    }
}

@ApiModel(description = "员工信息")//作用在实体类上,表示对类的说明
@Data
class Employee {
    @ApiModelProperty(value = "主键")//作用在属性上,描述属性信息
    private Long id;
}
上次更新 2025/9/9 20:40:32