SpringBoot整合Swagger

本文介绍如何在SpringBoot项目中整合Swagger,实现API文档的自动生成和在线测试,解决传统文档更新不及时、接口返回结果不明确等问题。通过配置依赖、Swagger配置类和使用相关注解,可以轻松管理和维护API文档。

SpringBoot整合Swagger

Swagger能解决手写API文档的几个痛点:

  1. 文档需要更新的时候,需要再次发送一份给前端,也就是文档更新交流不及时。
  2. 接口返回结果不明确
  3. 不能直接在线测试接口,通常需要使用工具,比如postman
  4. 接口文档太多,不好管理

一、依赖

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.6.1</version>
</dependency>
​
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.6.1</version>
</dependency>

二、Swagger配置类

其实这个配置类,只要了解具体能配置哪些东西就好了,毕竟这个东西配置一次之后就不用再动了。 特别要注意的是里面配置了api文件也就是controller包的路径,不然生成的文档扫描不到接口。

package cn.saytime;
​
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;
​
/**
 * @author zh
 * @ClassName cn.saytime.Swgger2
 * @Description
 * @date 2017-07-10 22:12:31
 */
@Configuration
public class Swagger2 {
​
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                // 扫描的包所在位置
                .apis(RequestHandlerSelectors.basePackage("com.example.demo"))
                // 扫描的 URL 规则
                .paths(PathSelectors.any())
                .build();
    }
    
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("springboot利用swagger构建api文档")
                .description("简单优雅的restfun风格,http://blog.youkuaiyun.com/saytime")
                .termsOfServiceUrl("http://blog.youkuaiyun.com/saytime")
                .version("1.0")
                .build();
    }
}

@Configuration注解该类,等价于XML中配置beans;用@Bean标注方法等价于XML中配置bean

Application.class 加上注解@EnableSwagger2 表示开启Swagger

package cn.saytime;
​
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
​
@SpringBootApplication
@EnableSwagger2
public class SpringbootSwagger2Application {
​
    public static void main(String[] args) {
        SpringApplication.run(SpringbootSwagger2Application.class, args);
    }
}

三、Restful 接口

package cn.saytime.web;
​
import cn.saytime.bean.JsonResult;
import cn.saytime.bean.User;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;
​
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
​
/**
 * @author zh
 * @ClassName cn.saytime.web.UserController
 * @Description
 */
@RestController
public class UserController {
​
    // 创建线程安全的Map
    static Map<Integer, User> users = Collections.synchronizedMap(new HashMap<Integer, User>());
​
    /**
     * 根据ID查询用户
     * @param id
     * @return
     */
    @ApiOperation(value="获取用户详细信息", notes="根据url的id来获取用户详细信息")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Integer", paramType = "path")
    @RequestMapping(value = "user/{id}", method = RequestMethod.GET)
    public ResponseEntity<JsonResult> getUserById (@PathVariable(value = "id") Integer id){
        JsonResult r = new JsonResult();
        try {
            User user = users.get(id);
            r.setResult(user);
            r.setStatus("ok");
        } catch (Exception e) {
            r.setResult(e.getClass().getName() + ":" + e.getMessage());
            r.setStatus("error");
            e.printStackTrace();
        }
        return ResponseEntity.ok(r);
    }
​
    /**
     * 查询用户列表
     * @return
     */
    @ApiOperation(value="获取用户列表", notes="获取用户列表")
    @RequestMapping(value = "users", method = RequestMethod.GET)
    public ResponseEntity<JsonResult> getUserList (){
        JsonResult r = new JsonResult();
        try {
            List<User> userList = new ArrayList<User>(users.values());
            r.setResult(userList);
            r.setStatus("ok");
        } catch (Exception e) {
            r.setResult(e.getClass().getName() + ":" + e.getMessage());
            r.setStatus("error");
            e.printStackTrace();
        }
        return ResponseEntity.ok(r);
    }
​
    /**
     * 添加用户
     * @param user
     * @return
     */
    @ApiOperation(value="创建用户", notes="根据User对象创建用户")
    @ApiImplicitParam(name = "user", value = "用户详细实体user", required = true, dataType = "User")
    @RequestMapping(value = "user", method = RequestMethod.POST)
    public ResponseEntity<JsonResult> add (@RequestBody User user){
        JsonResult r = new JsonResult();
        try {
            users.put(user.getId(), user);
            r.setResult(user.getId());
            r.setStatus("ok");
        } catch (Exception e) {
            r.setResult(e.getClass().getName() + ":" + e.getMessage());
            r.setStatus("error");
​
            e.printStackTrace();
        }
        return ResponseEntity.ok(r);
    }
​
    /**
     * 根据id删除用户
     * @param id
     * @return
     */
    @ApiOperation(value="删除用户", notes="根据url的id来指定删除用户")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long", paramType = "path")
    @RequestMapping(value = "user/{id}", method = RequestMethod.DELETE)
    public ResponseEntity<JsonResult> delete (@PathVariable(value = "id") Integer id){
        JsonResult r = new JsonResult();
        try {
            users.remove(id);
            r.setResult(id);
            r.setStatus("ok");
        } catch (Exception e) {
            r.setResult(e.getClass().getName() + ":" + e.getMessage());
            r.setStatus("error");
​
            e.printStackTrace();
        }
        return ResponseEntity.ok(r);
    }
​
    /**
     * 根据id修改用户信息
     * @param user
     * @return
     */
    @ApiOperation(value="更新信息", notes="根据url的id来指定更新用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long",paramType = "path"),
            @ApiImplicitParam(name = "user", value = "用户实体user", required = true, dataType = "User")
    })
    @RequestMapping(value = "user/{id}", method = RequestMethod.PUT)
    public ResponseEntity<JsonResult> update (@PathVariable("id") Integer id, @RequestBody User user){
        JsonResult r = new JsonResult();
        try {
            User u = users.get(id);
            u.setUsername(user.getUsername());
            u.setAge(user.getAge());
            users.put(id, u);
            r.setResult(u);
            r.setStatus("ok");
        } catch (Exception e) {
            r.setResult(e.getClass().getName() + ":" + e.getMessage());
            r.setStatus("error");
​
            e.printStackTrace();
        }
        return ResponseEntity.ok(r);
    }
​
    @ApiIgnore//使用该注解忽略这个API
    @RequestMapping(value = "/hi", method = RequestMethod.GET)
    public String  jsonTest() {
        return " hi you!";
    }
}

Json格式输出类 JsonResult.class

package cn.saytime.bean;
​
public class JsonResult {
​
    private String status = null;
​
    private Object result = null;
​
    // Getter Setter
}

实体User.class

package cn.saytime.bean;
​
import java.util.Date;
​
/**
 * @author zh
 * @ClassName cn.saytime.bean.User
 * @Description
 */
public class User {
​
    private int id;
    private String username;
    private int age;
    private Date ctm;
​
    // Getter Setter
}

项目结构:

https://i-blog.csdnimg.cn/blog_migrate/809857a65b392bc71f6069fe8d40d8ea.png

四、Swagger2文档

启动SpringBoot项目,访问 http://localhost:8080/swagger-ui.html

https://i-blog.csdnimg.cn/blog_migrate/08dc3cbdc5a73c0a3df53ae6a9d2ba28.png

五、Swagger注解

swagger通过注解表明该接口会生成文档,包括接口名、请求方法、参数、返回信息的等等。

  • @Api:修饰整个类,描述Controller的作用
  • @ApiOperation:描述一个类的一个方法,或者说一个接口
  • @ApiParam:单个参数描述
  • @ApiModel:用对象来接收参数
  • @ApiProperty:用对象接收参数时,描述对象的一个字段
  • @ApiResponseHTTP响应其中1个描述
  • @ApiResponsesHTTP响应整体描述
  • @ApiIgnore:使用该注解忽略这个API
  • @ApiError :发生错误返回的信息
  • @ApiImplicitParam:一个请求参数
  • @ApiImplicitParams:多个请求参数
@ApiOperation(value = "更新xxxxxx", notes = "根据xxxxxx更新xxxxxx")
@ApiImplicitParam(name = "xxxxxx", value = "订单xxxxxx实体", required = true, dataType = "xxxxxx")



@ApiOperation(value = "更新xxxxxx状态以及支付相关的方式及状态", notes = "根据xxxxxx更新xxxxxx")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "xxxxxx", value = "机票订单号", required = true, dataType = "String"),
			@ApiImplicitParam(name = "status", value = "ProductAir状态", required = true, dataType = "int"),
			@ApiImplicitParam(name = "xxxxxx", value = "订单支付状态", required = false, dataType = "Integer"),
			@ApiImplicitParam(name = "xxxxxxType", value = "订单支付方式", required = false, dataType = "Integer") })

 

Spring Boot 整合 Swagger 的详细教程如下: ### 安装 Swagger 先下载 Swagger,然后完成安装操作,不过引用中未提及具体的下载和安装步骤,一般在 Spring Boot 项目里可通过在 `pom.xml` 中添加 Swagger 相关依赖来完成安装,例如添加 Swagger2 和 Swagger UI 的依赖: ```xml <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 1. **编写接口**:在 Spring Boot 项目里编写 RESTful 接口,示例代码如下: ```java import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/api") public class HelloController { @GetMapping("/hello") public String hello() { return "Hello, Swagger!"; } } ``` 2. **启用 Swagger**:创建一个配置类来启用 Swagger,示例代码如下: ```java 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 public class SwaggerConfig { @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller")) .paths(PathSelectors.any()) .build() .apiInfo(apiInfo()); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("Spring Boot Swagger API") .description("API documentation for Spring Boot application") .version("1.0.0") .build(); } } ``` 3. **查看接口文档**:启动 Spring Boot 项目,在浏览器中访问 `http://localhost:8080/swagger-ui.html`(如果使用 Swagger2) 或者 `http://localhost:8080/doc.html`(如果使用 Swagger BootstrapUI),就能查看生成的接口文档 [^2]。 ### 高级使用 1. **描述数据模型**:借助 Swagger 的注解(如 `@ApiModel` 和 `@ApiModelProperty`)来描述数据模型,示例代码如下: ```java import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @ApiModel(description = "User model") public class User { @ApiModelProperty(value = "User ID", example = "1") private Long id; @ApiModelProperty(value = "User name", example = "John Doe") private String name; // Getters and setters } ``` 2. **描述枚举类型**:使用 `@ApiModel` 和 `@ApiModelProperty` 注解描述枚举类型,示例代码如下: ```java import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; @ApiModel(description = "User role") public enum UserRole { @ApiModelProperty(value = "Admin role") ADMIN, @ApiModelProperty(value = "User role") USER } ``` 3. **描述响应参数**:使用 `@ApiResponse` 注解描述响应参数,示例代码如下: ```java import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @Api(tags = "User API") @RestController @RequestMapping("/api/users") public class UserController { @ApiOperation(value = "Get user by ID") @ApiResponses(value = { @ApiResponse(code = 200, message = "Success", response = User.class), @ApiResponse(code = 404, message = "User not found") }) @GetMapping("/{id}") public User getUserById(Long id) { // Implementation return null; } } ``` ### 进阶使用 1. **配置全局参数**:若使用 Swagger BootstrapUI,可在“文档管理”中增加全局参数,包含添加 header 参数 [^3]。 2. **配置安全协议**:可在 Swagger 中配置安全协议,如 OAuth2 等。 3. **配置安全上下文**:配置安全上下文以确保接口的安全性。 4. **配置忽略参数**:配置忽略某些不需要显示的参数。 ### 整合 Spring Security 时的注意事项 在 Spring Boot 整合 Spring Security 和 Swagger 时,需要配置拦截的路径和放行的路径,要放行以下几个路径: ```java .antMatchers("/swagger**/**").permitAll() .antMatchers("/webjars/**").permitAll() .antMatchers("/v2/**").permitAll() .antMatchers("/doc.html").permitAll() ``` 如果使用了 bootstarp 的 Swagger UI 界面,需添加最后一个路径 [^1]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值