Swagger在Springboot项目中的使用

Swagger简介

前后端分离后,前后端之间依靠API交互,各自开发各自的。

好处:

  • 前后端相对独立,松耦合;
  • 前后端可以部署在不同的服务器上;
  • 可以有一套后端,多套前端。

前后端分离产生问题:

  • 前后端集成联调,前端人员和后端人员无法做到”及时协商,尽早解决“,最终导致问题集中爆发;

解决方案:

  • 首先制定schema[计划的大纲],实时更新最新API,降低集成的风险;
  • 早些年:制定word计划文档
  • 前后端分离:
    • 前端测试后端接口:postman
    • 后端提供接口,需要实时更新最新的消息及改动

Swagger

  • 号称世界上最流行的API框架
  • RestFul API文档在线自动生成工具=>API文档与API定义同步更新
  • 直接运行,可以在线测试API接口
  • 支持多种语言:(Java, PHP)

官网:https://swagger.io/

在项目中使用Swagger需要springfox jar包;

  • swagger2
  • ui

SpringBoot集成Swagger

1.新建一个SpringBoot项目,web项目

2.导入相关依赖

<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>

<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

3.编写测试代码hello工程

@RestController
@RequestMapping("/hello")
public class HelloController {

    @GetMapping("/test")
    public String hello() {
        return "hello";
    }
}

4.配置Swagger => Config

@Configuration
@EnableSwagger2 // 开启Swagger2,可以使用了
public class SwaggerConfig {
}

5.测试运行

在这里插入图片描述

配置Swagger

@Configuration
@EnableSwagger2 // 开启Swagger2,可以使用了
public class SwaggerConfig {

    // 配置了Swagger的Docket(摘要)的bean实例
    @Bean
    public Docket docket() {
        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo());
    }

    private ApiInfo apiInfo() {
        Contact contact = new Contact("宋永旗", "https://www.baidu.com", "sqzr316@163.com");
        return new ApiInfo( "宋永旗",
                "宋永旗的SwaggerAPI文档",
                "1.0",
                "https://www.baidu.com",
                contact,
                "Apache 2.0",
                "http://www.apache.org/licenses/LICENSE-2.0",
                new ArrayList<VendorExtension>());

    }
}

配置Swagger扫描接口

@Configuration
@EnableSwagger2 // 开启Swagger2,可以使用了
public class SwaggerConfig {

    // 配置了Swagger的Docket(摘要)的bean实例
    @Bean
    public Docket docket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                // enable表示是否启动swagger true启用,false关闭
                .enable(false)
                // 通过.select()方法得到ApiSelectorBuilder对象 来进一步选择过滤要扫描的接口
                .select()
                // .apis() 自定义要扫描的接口 传入一个请求处理的选择器
                .apis(RequestHandlerSelectors.basePackage("com.song.swagger.controller"))
                // .paths(PathSelectors.*()) 来自定义要显示的请求路径
                .paths(PathSelectors.ant("/hello/**"))
                .build();
    }

    private ApiInfo apiInfo() {
        Contact contact = new Contact("宋永旗", "https://www.baidu.com", "sqzr316@163.com");
        return new ApiInfo("宋永旗",
                "宋永旗的SwaggerAPI文档",
                "1.0",
                "https://www.baidu.com",
                contact,
                "Apache 2.0",
                "http://www.apache.org/licenses/LICENSE-2.0",
                new ArrayList<VendorExtension>());
    }
}

题目:实现swagger在生产环境不可用,开发环境可用。

思路:

  • 通过不同开发环境下的值,来传入swagger的enable(),确定是true还是false。

通过注释获取配置文件中的属性值:@Value(“${配置文件中属性名}”)

可以实现自动转格式,前提是不出现转格式异常,例如:类型不匹配TypeMisMatch,或者FormatException

其他思路:

  • 获取当前配置环境
  • 判断是否是需要开启swagger的环境
@Configuration
@EnableSwagger2 // 开启Swagger2,可以使用了
public class SwaggerConfig {

//    @Value("${swaggerenable}")
//    private boolean applicationEnableSwagger; // 可以通过配置文件的值来确定是否开启swagger

    // 配置了Swagger的Docket(摘要)的bean实例
    @Bean
    public Docket docket(Environment environment) { // Environment是spring的core包中的,注意不要导错包
        // 设置要显示的swagger环境
        Profiles profiles = Profiles.of("dev", "test");
        // 通过环境类 监控是否是 指定的profiles
        boolean flag = environment.acceptsProfiles(profiles);
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                // enable表示是否启动swagger true启用,false关闭
                .enable(flag)
                // 通过.select()方法得到ApiSelectorBuilder对象 来进一步选择过滤要扫描的接口
                .select()
                // .apis() 自定义要扫描的接口 传入一个请求处理的选择器
                .apis(RequestHandlerSelectors.basePackage("com.song.swagger.controller"))
                // .paths(PathSelectors.*()) 来自定义要显示的请求路径
                .paths(PathSelectors.ant("/hello/**"))
                .build();
    }

    private ApiInfo apiInfo() {
        Contact contact = new Contact("宋永旗", "https://www.baidu.com", "sqzr316@163.com");
        return new ApiInfo("宋永旗",
                "宋永旗的SwaggerAPI文档",
                "1.0",
                "https://www.baidu.com",
                contact,
                "Apache 2.0",
                "http://www.apache.org/licenses/LICENSE-2.0",
                new ArrayList<VendorExtension>());
    }
}

配置swagger中API文档的分组

配置多个Docket的Bean即可,不同的模块中的接口,放在不同的分组中,方便管理查看。

@Configuration
@EnableSwagger2 // 开启Swagger2,可以使用了
public class SwaggerConfig {


    @Bean
    public Docket docket1() {
        // new Docket(指定swagger的版本)
        return new Docket(DocumentationType.SWAGGER_2).groupName("永旗-登录模块");
    }

//    @Value("${swaggerenable}")
//    private boolean applicationEnableSwagger; // 可以通过配置文件的值来确定是否开启swagger

    // 配置了Swagger的Docket(摘要)的bean实例
    @Bean
    public Docket docket(Environment environment) { // Environment是spring的core包中的,注意不要导错包
        // 设置要显示的swagger环境
        Profiles profiles = Profiles.of("dev", "test");
        // 通过环境类 监控是否是 指定的profiles
        boolean flag = environment.acceptsProfiles(profiles);
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .groupName("永旗-搜索模块")
                // enable表示是否启动swagger true启用,false关闭
                .enable(flag)
                // 通过.select()方法得到ApiSelectorBuilder对象 来进一步选择过滤要扫描的接口
                .select()
                // .apis() 自定义要扫描的接口 传入一个请求处理的选择器
                .apis(RequestHandlerSelectors.basePackage("com.song.swagger.controller"))
                // .paths(PathSelectors.*()) 来自定义要显示的请求路径
                .paths(PathSelectors.ant("/hello/**"))
                .build();
    }

    private ApiInfo apiInfo() {
        Contact contact = new Contact("宋永旗", "https://www.baidu.com", "sqzr316@163.com");
        return new ApiInfo("宋永旗",
                "宋永旗的SwaggerAPI文档",
                "1.0",
                "https://www.baidu.com",
                contact,
                "Apache 2.0",
                "http://www.apache.org/licenses/LICENSE-2.0",
                new ArrayList<VendorExtension>());
    }
}

Swagger常用注释注解:

只要swaggerAPI文档的接口中存在返回实体类,就会把返回的实体类显示在swagger页面中的Model中。

实体类相关注释:

@Data
@Component
@ApiModel("用户实体类")
public class User {
    @ApiModelProperty("用户名")
    private String name;
    @ApiModelProperty("年龄")
    private int age;
}

接口的各种注释注解:

@RestController
@RequestMapping("/hello")
public class HelloController {

    @GetMapping("/test")
    public String hello() {
        return "hello";
    }

    @GetMapping("/user/{id}")
    @ApiOperation("获取用户实体类")
    public User getUser(@ApiParam("参数id") @PathVariable Integer id) {
        return new User();
    }

    @ApiOperation("添加User用户")
    @PostMapping("/user")
    public User updateUser(@ApiParam("填写用户信息") User user) {
        return user;
    }
}

总结

  • 我们可以通过Swagger给一些比较难理解的属性或者接口增加注释信息
  • 接口文档实时更新
  • 可以在线测试

Swagger是一个优秀的工具,几乎所有的大公司都有使用它

【注意】:在正式发布的时候,关闭Swagger。这是为了安全考虑,也是为了节约运行时内存。

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Knife4j是基于Swagger的增强UI实现,可以帮助我们生成API文档以及测试接口,使接口文档更加直观、易懂。在SpringBoot项目,我们可以通过以下步骤来实际使用Knife4j: 1.添加Knife4j依赖 在pom.xml文件添加以下依赖: ``` <dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>knife4j-spring-boot-starter</artifactId> <version>3.0.2</version> </dependency> ``` 2.配置SwaggerSpringBoot项目,我们可以通过@Configuration注解来配置Swagger,例如: ``` @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket docket() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(new ApiInfoBuilder() .title("API文档") .description("这是一个Swagger API文档") .version("1.0.0") .build()) .select() .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller")) .paths(PathSelectors.any()) .build(); } } ``` 其,@EnableSwagger2注解表示开启Swagger功能,@Bean注解表示将该方法返回的对象注册到Spring容器,Docket对象表示用于配置Swagger的构建器,apiInfo方法用于设置文档基本信息,select方法用于指定要扫描的接口,这里我们扫描com.example.demo.controller包下的接口。 3.访问Knife4j页面 启动SpringBoot项目后,访问http://localhost:8080/doc.html即可进入Knife4j页面,可以看到自动生成的接口文档以及测试接口的功能。通过点击接口名称,可以查看该接口的详细信息,包括请求参数、响应参数等。同时,我们也可以在页面上进行接口测试,方便调试接口。 总的来说,使用Knife4j可以让接口文档更加直观、易懂,同时也方便了前后端的沟通与开发。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值