在 SprintBoot 中集成 Swagger
1、引入 Swagger 相关依赖
<!--引入Swagger依赖-->
<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、编写一个Hello接口
@RestController
public class HelloController {
@RequestMapping("/hello")
public String hello(){
return "helllo";
}
}
3、配置Swagger
@Configuration
@EnableSwagger2 //开启Swagger2
public class SwaggerConfig {
}
4、测试运行Swagger,访问:http://localhost:8080/swagger-ui.html
5、Swagger 的相关配置
@Configuration
@EnableSwagger2 //此注解用来开启Swagger2
public class SwaggerConfig {
//配置 Swagger 的Docket bean实例
@Bean
public Docket createRestApi(Environment environment){
//org.springframework.core.env.Environment 项目环境
//根据项目环境判断是否开启Swagger,dev和test开启Swagger,prod不开启
Profiles profiles = Profiles.of("dev","test");
boolean eFlag = environment.acceptsProfiles(profiles);
return new Docket(DocumentationType.SWAGGER_2)
//enable() 是否开启 Swagger
.enable(eFlag)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.zhangstudy.controller"))
//paths() 过滤某个路径
.paths(PathSelectors.any())
.build();
}
//配置ApiInfo信息
public ApiInfo apiInfo(){
return new ApiInfoBuilder()
.title("SwaggerApi文档")
.description("学无止境")
.termsOfServiceUrl("https://blog.csdn.net/qq_45090834?type=blog")
.version("1.0")
.build();
}
}
关闭Swagger时: