[java]62、Swagger

2022-11-06  本文已影响0人  史记_d5da

1、Swagger的使用

Swagger可以快速生成接口文档,极大地节省了开发人员编写接口文档的时间。
1、pom.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>

官方推荐的是starter

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>

2、代码配置

@Configuration
@EnableSwagger2
public class SwaggerCfg implements InitializingBean {
    @Autowired
    private Environment environment;
    @Bean
    public Docket docket(Environment environment) {
        return baseDocket()
                .groupName("default")
                .apiInfo(apiInfo("小码哥驾考系统接口文档", "详细的接口文档"))
                .select()
                .paths(PathSelectors.ant("dictItems/**")).build();
    }
    private Docket baseDocket() {
        Parameter token = new ParameterBuilder()
                .name("token")
                .description("用户登录令牌")
                .parameterType("query")
                .modelRef(new ModelRef("String"))
                .build();
        return new Docket(DocumentationType.SWAGGER_2)
                .globalOperationParameters(Arrays.asList(token))
                .ignoredParameterTypes(
                        HttpSession.class,
                        HttpServletRequest.class,
                        HttpServletResponse.class)
                .enable(true);
    }
    private ApiInfo apiInfo(String title, String description) {
        return new ApiInfoBuilder()
                .title("小码哥驾考系统接口文档")
                .description("详细的接口文档")
                .version("1.0.0")
                .build();
    }
}

在使用starter配置时,需要去掉@EnableSwagger2
3、访问文档
如果使用了starter
http://localhost:8080/swagger-ui/index.html
如果没有使用starter
http://localhost:8080/swagger-ui.html
4、分组

new Docket(DocumentationType.SWAGGER_2)
        .groupName("default")
        .apiInfo(apiInfo("小码哥驾考系统接口文档", "详细的接口文档"))
        .select()
        .paths(PathSelectors.ant("dictItems/**")).build();

5、全局参数配置

Parameter token = new ParameterBuilder()
                .name("token")
                .description("用户登录令牌")
                .parameterType("query")
                .modelRef(new ModelRef("String"))
                .build();
new Docket(DocumentationType.SWAGGER_2)
                .globalOperationParameters(Arrays.asList(token))

2、常用注解

@Api(tags = "模块名", description = "描述",):用在Controller上
@ApiOperation(value = "作用", notes = "备注"):用在请求方法上
@ApiModel(value = "实体名", description = "备注"):用在entity上
@ApiModelProperty(value = "属性名", hidden = false, required = false):用在entity的属性上
@ApiParam(value = "参数名", hidden = false, required = false):用在请求参数上
@ApiImplicitParams@ApiImplicitParam:用在请求方法上,描述参数信息
@ApiResponses@ApiResponse:用在请求方法上,描述响应信息

上一篇下一篇

猜你喜欢

热点阅读