无涯

无所谓无 无所谓有

Spring-Boot快速集成Swagger

前言

以前用Swagger总是用springFox封装的SDK,但是好像一直没怎么更新了,相应的Spring Boot Starter一直没有官方的包,最近突然发现官方发布了一个Starter。

引入依赖

1
2
3
4
5
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
<dependency>

开启Swagger UI

1
2
3
4
5
6
7
8
@EnableOpenApi
@SpringBootApplication
public class DemoApplication {

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

添加一些注解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65

/**
* 用户管理
*
* @author oneyoung
*/
@RestController
@RequestMapping(value = "/api/user", produces = MediaType.APPLICATION_JSON_VALUE)
@Api(tags = "用户管理")
public class UserController {

private static final AtomicLong atomic = new AtomicLong();
private static final Map<Long, User> USER_MAP = new HashMap<>();

@PostMapping
@ApiOperation(value = "创建用户", notes = "这是一个创建用户的接口")
public ResponseEntity<User> createUser(
@RequestBody
@ApiParam(value = "用户实体对象", required = true) User user) {
long id = atomic.incrementAndGet();
user.setId(id);
USER_MAP.put(id, user);
return new ResponseEntity<>(user, HttpStatus.OK);
}

@PostMapping("/createWithArray")
@ApiOperation(value = "批量创建用户")
public ResponseEntity<Boolean> createUsersWithArrayInput(@ApiParam(value = "List of user object", required = true)
User[] users) {
for (User user : users) {
long id = atomic.getAndIncrement();
user.setId(id);
USER_MAP.put(id, user);
}
return ResponseEntity.ok(true);
}

@PostMapping(value = "/createWithList")
@ResponseBody
@ApiOperation(value = "Creates list of users with given input array")
public ResponseEntity<Boolean> createUsersWithListInput(
@ApiParam(value = "List of user object", required = true) List<User> users) {
for (User user : users) {
long id = atomic.getAndIncrement();
user.setId(id);
USER_MAP.put(id, user);
}
return ResponseEntity.ok(true);
}

@RequestMapping(value = "/{username}", method = PUT)
@ResponseBody
@ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.")
@ApiResponses(value = {
@ApiResponse(code = 400, message = "Invalid user supplied"),
@ApiResponse(code = 404, message = "User not found")})
public ResponseEntity<String> updateUser(
@ApiParam(value = "name that need to be deleted", required = true)
@PathVariable("username") String username,
@ApiParam(value = "Updated user object", required = true) User user) {

return null;
}

}

访问UI

http://localhost:8080/swagger-ui/index.html

image-20210801171730465

结尾

这只是快速引入Swagger的例子,还有很多细节没有写出来,比如

  • 如果需要将api分类以及进行权限认证等,需要将springfox.documentation.spring.web.plugins.Docket注册为Bean

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    package com.example.demo.config;

    import org.springframework.context.annotation.Bean;
    import springfox.documentation.builders.ApiInfoBuilder;
    import springfox.documentation.builders.PathSelectors;
    import springfox.documentation.builders.RequestParameterBuilder;
    import springfox.documentation.service.*;
    import springfox.documentation.spi.DocumentationType;
    import springfox.documentation.spi.service.contexts.SecurityContext;
    import springfox.documentation.spring.web.plugins.Docket;

    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;

    /**
    * SwaggerConfig
    *
    * @author oneyoung
    * @since 2021/7/28 11:40 下午
    */
    //@EnableOpenApi
    //@Configuration
    public class SwaggerConfig {
    @Bean
    public Docket petApi() {
    RequestParameterBuilder requestParameterBuilder = new RequestParameterBuilder();
    List<RequestParameter> parameters = new ArrayList<>();
    requestParameterBuilder
    .name("Cookie")
    .in(ParameterType.HEADER)
    .required(false);
    parameters.add(requestParameterBuilder.build());
    return new Docket(DocumentationType.SWAGGER_2)
    .groupName("user")
    .apiInfo(apiInfo())
    .select()
    .paths(PathSelectors.any())
    .build()
    .globalRequestParameters(parameters)
    .securitySchemes(Collections.singletonList(new ApiKey("Cookie", "cookie", "header")))
    .securityContexts(securityContexts())
    ;
    }

    private List<SecurityContext> securityContexts() {
    return Collections.singletonList(
    SecurityContext.builder()
    .securityReferences(defaultAuth())
    .operationSelector(operationContext -> true)
    .build()
    );
    }

    List<SecurityReference> defaultAuth() {
    AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
    AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
    authorizationScopes[0] = authorizationScope;
    return Collections.singletonList(
    new SecurityReference("Cookie", authorizationScopes));
    }

    private ApiInfo apiInfo() {
    return new ApiInfoBuilder()
    .title("Springfox petstore API")
    .description("Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum " +
    "has been the industry's standard dummy text ever since the 1500s, when an unknown printer "
    + "took a " +
    "galley of type and scrambled it to make a type specimen book. It has survived not only five " +
    "centuries, but also the leap into electronic typesetting, remaining essentially unchanged. " +
    "It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum " +
    "passages, and more recently with desktop publishing software like Aldus PageMaker including " +
    "versions of Lorem Ipsum.")
    .termsOfServiceUrl("http://springfox.io")
    .contact(new Contact("springfox", "", ""))
    .license("Apache License Version 2.0")
    .licenseUrl("https://github.com/springfox/springfox/blob/master/LICENSE")
    .version("2.0")
    .build();
    }

    }
  • 生产环境最好不要暴露swagger地址,可以添加如下配置屏蔽

    1
    springfox.documentation.swagger-ui.enabled=false
  • 日常环境需要绕过鉴权,需要将swagger资源加入白名单

    • /swagger-resources/**
    • /v3/api-docs