


<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>



@Configuration
@EnableSwagger2 //开启Swagger2
public class SwaggerConfig {
//配置了Swagger的docket实例
@Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//RequestHandlerSelectors 配置要扫描接口的方式
//basePackage 指定要扫描的包
//.any() 扫描全部
//.none() 都不扫描
//.withClassAnnotation() 扫描类上注解 参数是一个注解的反射对象
//.withMethodAnnotation() 扫描方法上的注解 比如RestController
.apis(RequestHandlerSelectors.basePackage("com.lin.springswagger.controller"))
//.path() 过滤什么路径 只扫描
//.paths(PathSelectors.ant("/ccgg/**"))
.build();
}
//配置自己的Swagger信息
private ApiInfo apiInfo() {
//作者信息
Contact contact = new Contact("ccgg", "www.ccgg.com", "ccgg@qq.ocm");
return new ApiInfo(
"ccgg!",
"再小的帆也能远航",
"v1.0",
"https://www.ccgg.com",
contact,
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList<VendorExtension>());
}
}
配置是否启动Swagger





代码
/**
* @Author lin
* @Date 2020/10/20 22:48
*/
@Configuration
@EnableSwagger2 //开启Swagger2
public class SwaggerConfig {
//配置了Swagger的docket实例
@Bean
public Docket docket(Environment environment) {
//设置要显示的swagger环境
Profiles profiles = Profiles.of("dev","test");
//通过environment.acceptsProfiles 判断是否自己处在设定的环境
boolean flag = environment.acceptsProfiles(profiles);
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
//是否开启swagger默认是开启的
.enable(flag)
.select()
//RequestHandlerSelectors 配置要扫描接口的方式
//basePackage 指定要扫描的包
//.any() 扫描全部
//.none() 都不扫描
//.withClassAnnotation() 扫描类上注解 参数是一个注解的反射对象
//.withMethodAnnotation() 扫描方法上的注解 比如RestController
.apis(RequestHandlerSelectors.basePackage("com.lin.springswagger.controller"))
//.path() 过滤什么路径 只扫描
//.paths(PathSelectors.ant("/ccgg/**"))
.build();
}
//配置自己的Swagger信息
private ApiInfo apiInfo() {
//作者信息
Contact contact = new Contact("ccgg", "www.ccgg.com", "ccgg@qq.ocm");
return new ApiInfo(
"ccgg!",
"再小的帆也能远航",
"v1.0",
"https://www.ccgg.com",
contact,
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList<VendorExtension>());
}
}

实体类配置
1.无任何配置



2.实体类添加文档注释


3.方法添加注释


4.入参注释




测试功能





本文档介绍了如何在Spring Boot项目中配置和使用Springfox Swagger2,以生成RESTful API的文档。首先引入了Swagger2和Swagger-UI的依赖,然后通过@Configuration和@EnableSwagger2注解开启Swagger2。在SwaggerConfig类中,定义了一个Docket Bean,配置了扫描的包路径、API信息以及是否根据环境启用Swagger。同时,展示了如何在实体类、方法和参数上添加注解以提供详细的API文档信息。最后,提供了测试功能以验证Swagger的配置和功能。

被折叠的 条评论
为什么被折叠?



