使用Swagger2构建强大的API文档

本文详细介绍如何在SpringBoot项目中整合Swagger2,包括添加依赖、编写配置类及控制器注解,同时提供生产环境中禁用Swagger2的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Swagger2

一、整合Swagger2

1.1、在pom.xml中添加依赖

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

1.2、编写swagger2配置类

@Configuration
@EnableSwagger2
//@Profile({"dev","test"})
@ConditionalOnProperty(name = "swagger.enable", havingValue = "true")
public class Swagger2 {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.controller"))
                .paths(PathSelectors.any())
                .build();
    }
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Spring Boot中使用Swagger2构建RESTful APIs")
                .description("更多Spring Boot相关文章请关注:http://blog.didispace.com/")
                .termsOfServiceUrl("http://localhost:8090/swagger-ui.html")
                .contact(new Contact("qixin","","330553352@qq.com"))
                .version("1.0")
                .build();
    }
}

1.3、添加文件内容

@Api(value = "swagger2", description = "swagger2", position = 100, protocols = "http")
@Resource(name = "swagger2")
public class WgsjzlqsyController {

    @GetMapping("/list")
    @ApiOperation(value="swagger2", notes="swagger2",httpMethod = "GET")
    public List<Wgsjzlqsy> list(){

        return service.findList();
    }
}

二、生产环境下禁用Swagger2

2.1、方式一

在Swagger2配置类中指定环境:@Profile({“dev”,“test”})

2.2、方式二

  • 在配置文件中(application.properties)设置开关:
    #swagger开关
    swagger.enable=true
  • 在Swagger2配置类中使用Swagger2开关功能:
    @ConditionalOnProperty(name = “swagger.enable”, havingValue = “true”)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值