[java]62、Swagger

1、Swagger的使用

Swagger可以快速生成接口文档,极大地节省了开发人员编写接口文档的时间。
1、pom.xml中添加以下两个库


    io.springfox
    springfox-swagger2
    2.9.2


    io.springfox
    springfox-swagger-ui
    2.9.2

官方推荐的是starter


    io.springfox
    springfox-boot-starter
    3.0.0

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:用在请求方法上,描述响应信息

你可能感兴趣的:([java]62、Swagger)