swagger的简单入门和使用

一、什么是swagger?

Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 restful 风格的 Web 服务。
总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法、参数和模型紧密集成到服务器端的代码,允许 API 来始终保持同步。Swagger 让部署管理和使用功能强大的 API 从未如此简单。

二、如何使用swagger?

本文主要介绍在springboot中swagger的使用。

1、导入依赖:
<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>

通过Swagger UI生成网页版的接口文档,可以在上面做简单的接口调试 。功能还是比较强大的。

2、配置swagger

在config包下面新建一个class类。

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket docket(Environment environment) {
        //设置要显示的swagger环境
        Profiles profiles = Profiles.of("dev");
        //判断自己是否处于设定的环境中
        boolean flag = environment.acceptsProfiles(profiles);

        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo()).groupName("daodao");
                //通过flag判断该环境是否能访问swagger
                //.enable(flag)
                //.select()
                //any():扫描全部
                //none():都不扫描
                //basePackage():扫描指定的包
                //withClassAnnotation():扫描类上的注解,参数是注解的反射对象(restController)
                //withMethodAnnotation:扫描方法上的注解
//                .apis(RequestHandlerSelectors.withMethodAnnotation(GetMapping.class))
//                //过滤什么路径
//                .paths(PathSelectors.ant("/daodao/**"))
//                .build();
    }

    public ApiInfo apiInfo() {
        Contact contact = new Contact("刀刀","localhost:8080","123455@qq.com");
        return new ApiInfo("刀刀",
                "即使再小的帆也能远航",
                "1.0",
                "localhost:8080",
                contact,
                "apache2.0",
                "wangjiansuoyou",
                new ArrayList<>());
    }
}

配置完之后显示效果如下:登入http://localhost:8080/swagger-ui.html查看
在这里插入图片描述

3、作一个简单测试

实体类:

@Data
@AllArgsConstructor
@NoArgsConstructor
@ApiModel(description = "新闻")
public class News implements Serializable {
    @ApiModelProperty(value = "新闻标题",name = "title")
    private String title;
    @ApiModelProperty(value = "新闻内容",name = "content")
    private String content;
}

controller层(service和dao层就不写了,简单的查询)

@RestController
public class NewsController {
    @Autowired
    private INewsService newsService;


    @GetMapping("/news")
    public List queryAll() throws Exception {
        ModelAndView m = new ModelAndView();
        List<News> newsList =  newsService.queryAll();
        return newsList;
    }
	
	//要测试的方法
    @PostMapping("/newsByTitle")
    public String queryByTitle(@ApiParam @RequestBody String title) throws Exception {
        System.out.println("title is "+title);
        String content = newsService.queryByTitle(title);
        System.out.println(content);
        return content;
    }
}

测试一下:
在这里插入图片描述
总的来说,swagger的基本用法就是如此了。不是很难。
那么,swagger的优点也是可以看得到的,便利了前后端分离,在线自动生成文档等。但是主要在生产环境中要将swagger隐藏或者删除,否则会有安全隐患。

4、swagger常用注解

常用注解:

  • @Api()用于类;
    表示标识这个类是swagger的资源
  • @ApiOperation()用于方法;
    表示一个http请求的操作
  • @ApiParam()用于方法,参数,字段说明;
    表示对参数的添加元数据(说明或是否必填等)
  • @ApiModel()用于类
    表示对类进行说明,用于参数用实体类接收
  • @ApiModelProperty()用于方法,字段
    表示对model属性的说明或者数据操作更改
  • @ApiIgnore()用于类,方法,方法参数
    表示这个方法或者类被忽略
  • @ApiImplicitParam() 用于方法
    表示单独的请求参数
  • @ApiImplicitParams() 用于方法,包含多个 @ApiImplicitParam
### Swagger入门教程与实战案例 #### 了解Swagger及其组件 Swagger 是一种用于设计、构建、记录使用 RESTful 风格 Web 服务的开源框架[^1]。它由多个部分组成,包括但不限于 Swagger UI Springfox。 - **Swagger UI**: 提供了一个直观的界面来展示 API 文档并允许开发者测试这些 API 的功能。 - **Springfox**: 这是一个基于 Java 注解的方式来自动生成 Swagger 文档的库,在 Spring Boot 或 Spring MVC 应用程序中非常有用。 #### 安装配置 对于想要在Java环境中集成Swagger的应用来说: - 在 `pom.xml` 文件里加入依赖项以便于支持 Swagger 功能: ```xml <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> </dependency> ``` - 接着创建一个简单的控制器类,并添加必要的注释以使 Swagger 能够识别端点信息: ```java import io.swagger.annotations.Api; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/api") @Api(tags = "Example Controller", description = "This is an example controller.") public class ExampleController { @GetMapping("/hello") public String hello() { return "Hello, world!"; } } ``` #### 实际应用场景 当涉及到具体的业务逻辑时,可以采用不同的方法论来进行工作流的设计: - 如果是从零开始建立新的API,则可以选择先定义好所有的请求路径以及参数格式等细节内容,再利用工具如 Swagger Editor 来生成相应的代码模板[^4]; - 对已经存在的RESTful API进行文档化处理的话,可以直接借助插件或命令行工具扫描现有资源从而得到完整的描述文件; - 当作为第三方使用者去消费某个特定平台所提供的公开接口时,只需下载对应的客户端SDK即可轻松发起调用了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值