Swagger (API框架,API 文档 与API 定义同步更新)
1.依赖

<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.5.7</version> <relativePath/> <!-- lookup parent from repository --> </parent> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency>
2.注册bean
@Configuration //表明配置类 @EnableSwagger2 //开启 public class SwaggerConfig { @Bean //配置了Swagger的Bean实例 public Docket docket(Environment environment){ //不同环境下Swagger开启或关闭 //获取项目环境 Profiles of = Profiles.of("dev", "test"); // 判断当前是否处于该环境 // 判断是否在这个环境下,是则true boolean flag = environment.acceptsProfiles(of); return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select()// 通过.select()方法,去配置扫描接口,RequestHandlerSelectors 配置如何扫描接口 .apis(RequestHandlerSelectors.basePackage("com.ljm.controller")) //.basePackage 指定包 (常用) // .any() 全部的包 // .none() 不扫描接口 // 通过方法上的注解扫描,如withMethodAnnotation(GetMapping.class)只扫描get请求 //.withMethodAnnotation(final Class<? extends Annotation> annotation) // 通过类上的注解扫描,如.withClassAnnotation(Controller.class)只扫描有controller注解的类中的接口 //withClassAnnotation(final Class<? extends Annotation> annotation) // 配置如何通过path过滤,即这里只扫描请求以/kuang开头的接口 // .paths(PathSelectors.ant("/kuang/**")) .build() .groupName("akagi") //会在浏览器右上角选择框内出现 可以设置多个docket用不同的groupName .enable(flag) //关闭swagger,不能在浏览器访问 ; } }
3.配置

//配置页面信息 private ApiInfo apiInfo(){ return new ApiInfo("我的Api文档", "头顶的星空和", "1.0", "www.baidu.com", new Contact("AKAGI", "URL", "7788@qq.com"), // 作者信息 "Apache 2.0", "http://www.apache.org/licenses/LICENSE-2.0", new ArrayList()); }
4.测试
http://localhost:8080/swagger-ui.html
5.配置多个分组 (同时也可以配置多个ApiInfo)

@Bean public Docket docket1() { return new Docket(DocumentationType.SWAGGER_2).groupName("group1"); } @Bean public Docket docket2() { return new Docket(DocumentationType.SWAGGER_2).groupName("group2"); } @Bean public Docket docket3() { return new Docket(DocumentationType.SWAGGER_2).groupName("group3"); }
注释
实体类
@ApiModel
@ApiModelProperty
@ApiOperation
@ApiParam
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术