使用Swagger 管理项目API

背景简介

当前的业务以前后端分离为主,在接口联调时,手动更新接口信息繁琐切容易出错,使用swagger 可简化api文档生成,接下来基于springboot项目, 以一个示例简介如何使用以及遇到的一些问题

使用

 1、pom依赖

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>

2、工程配置

在程序入口使用配置

@EnableSwagger2
@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication .class, args);
    }

}

编写配置类

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
public class Swagger2 {


    //swagger2的配置文件,这里可以配置swagger2的一些基本的内容,比如扫描的包等等
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //为当前包路径
                .apis(RequestHandlerSelectors.basePackage("com.test"))
                .paths(PathSelectors.any())
                .build();
    }
    //构建 api文档的详细信息函数,注意这里的注解引用的是哪个
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                //页面标题
                .title(" API Document.")
                //版本号
                .version("1.0")
                //描述
                .description("API 描述")
                .build();
    }
}

完成以上步骤即配置完成

3、使用方法

启动项目,访问 http://127.0.0.1:8080/swagger-ui.html 既可

拓展内容

以上内容即完成了swagger的配置,但以上内容在生产环境中暴露了就存在一定的风险,所以需要在生产环境中关系swagger配置。查阅资料后在application.yml中增加配置

swagger:
  enable: false

但是却没有生效

查阅资料后使用@ConditionalOnProperty 可使配置不生效,该注解主要通过name, havingValue两个值来判断该配置是否生效,其中name从配置文件中读取值,该值再与havingValue进行比较

1. 若结果相同,则返回true,该配置生效

2. 若结果不同,则返回false,该配置不生效

基于这个注解,修改配置文件为



import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@ConditionalOnProperty(name = "swagger.enable", havingValue = "true")
public class Swagger2 {

    @Value("${swagger.enable}")
    private Boolean enable;
    //swagger2的配置文件,这里可以配置swagger2的一些基本的内容,比如扫描的包等等
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //为当前包路径
                .apis(RequestHandlerSelectors.basePackage("com.test"))
                .paths(PathSelectors.any())
                .build();
    }
    //构建 api文档的详细信息函数,注意这里的注解引用的是哪个
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                //页面标题
                .title("API Document.")
                //版本号
                .version("1.0")
                //描述
                .description("API 描述")
                .build();
    }
}

但重启后仍能访问swagger页面,配置仍然没有生效,检查后,推测是@EnableSwagger2 写在 程序入口导致失效,修改至配置页面成功生效,最终代码如下

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
@ConditionalOnProperty(name = "swagger.enable", havingValue = "true")
public class Swagger2 {

    @Value("${swagger.enable}")
    private Boolean enable;
    //swagger2的配置文件,这里可以配置swagger2的一些基本的内容,比如扫描的包等等
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //为当前包路径
                .apis(RequestHandlerSelectors.basePackage("com.test"))
                .paths(PathSelectors.any())
                .build();
    }
    //构建 api文档的详细信息函数,注意这里的注解引用的是哪个
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                //页面标题
                .title(" API Document.")
                //版本号
                .version("1.0")
                //描述
                .description("API 描述")
                .build();
    }
}

至此,配置生效,此处遗留两个待补充项,一位@ConditionalOnProperty 详解,一为spring启动机制,日后填坑~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Swagger是一款流行的API设计工具,它可以帮助我们更轻松地设计、构建和测试APISwagger2是Swagger的一个版本,它可以生成API接口文档,这样我们就可以更清晰地了解API使用方法。 下面是使用Swagger2生成API接口文档的步骤: 1. 在项目中添加Swagger2依赖 在Maven项目中,可以在pom.xml文件中添加以下依赖: ``` <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> ``` 2. 配置Swagger2 在Spring Boot项目中,可以在application.properties或application.yml文件中添加以下配置: ``` # Swagger2配置 swagger2.enabled=true # 启用Swagger2 swagger2.title=API接口文档 # 文档标题 swagger2.description=API接口文档 # 文档描述 swagger2.version=1.0 # 文档版本 swagger2.basePackage=com.example.demo # 扫描的包路径 ``` 3. 编写API接口 在Spring Boot项目中,可以使用Spring MVC的注解来编写API接口,例如: ``` @RestController @RequestMapping("/api") @Api(tags = "用户管理") public class UserController { @GetMapping("/users") @ApiOperation("获取用户列表") public List<User> getUsers() { // TODO: 查询用户列表 return null; } @GetMapping("/users/{id}") @ApiOperation("根据ID获取用户") @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long") public User getUserById(@PathVariable Long id) { // TODO: 根据ID查询用户 return null; } @PostMapping("/users") @ApiOperation("创建用户") @ApiImplicitParam(name = "user", value = "用户信息", required = true, dataType = "User") public User createUser(@RequestBody User user) { // TODO: 创建用户 return null; } @PutMapping("/users/{id}") @ApiOperation("更新用户") @ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long"), @ApiImplicitParam(name = "user", value = "用户信息", required = true, dataType = "User") }) public User updateUser(@PathVariable Long id, @RequestBody User user) { // TODO: 更新用户 return null; } @DeleteMapping("/users/{id}") @ApiOperation("删除用户") @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long") public void deleteUser(@PathVariable Long id) { // TODO: 删除用户 } } ``` 4. 访问Swagger2文档 在启动Spring Boot应用程序后,可以在浏览器中访问以下URL以查看Swagger2生成的API接口文档:http://localhost:8080/swagger-ui.html 在Swagger2的文档页面中,可以查看接口的详细信息,包括请求和响应的参数、请求方式、请求路径等。同时,我们也可以在页面中测试API接口。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值