swagger的入门教程

一. 创建一个swagger

1.springboot的pom.xml中导入依赖:

		<!--swagger-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
        </dependency>
        <!--swagger ui-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
        </dependency>

2.在config包下,创建Swagger2Config类:
两个注解非常重要:@Configuration和EnableSwagger2

@Configuration  //配置类
@EnableSwagger2  //swagger注解
public class Swagger2Config {
    @Bean
    public Docket adminApiConfig(){
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("adminApi")
                .apiInfo(adminApiInfo())
                .select()
                //直线admin路径下的也页面
                .paths(Predicates.and(PathSelectors.regex("/admin/.*")))
                .build();
    }

    private ApiInfo adminApiInfo(){
        return new ApiInfoBuilder()
                .title("xxx后台管理系统——API文档")
                .description("本文档描述了xxx后台管理系统接口")
                .version("1.0")
                .contact(new Contact("作者名字","url","联系方式(邮箱)"))
                .build();
    }

}

3.在springboot启动类上添加扫描包,扫描包含config的路径:

@SpringBootApplication
@ComponentScan({"com.xxx"})
public class ServiceCoreApplication {
    public static void main(String[] args) {
        SpringApplication.run(ServiceCoreApplication.class, args);
    }
}

4.启动服务器查看文档接口:
http://localhost:8080/swagger-ui.html
在这里插入图片描述

二. 常用注解:

1.实体类注解:pojo实体类中可以添加一些自定义设置,例如:

@ApiModelProperty(value = "创建时间", example = "2019-01-01 8:00:00")
private LocalDateTime createTime;

2.controller注解:
定义在类上:

@Api(tags="积分管理")

定义在方法上:


@ApiOperator("积分等级列表")
@GetRequest("/list")
public List<Entity> list(){}

@ApiOperator(value="根据id删除积分等级",notes="逻辑删除")
@DeleteRequest("/delete/{}")
public void delete(@PathVariable Integer id){}

定义在参数上:

public void delete(@PathVariable 
@ApiParam(value="数据id",required= true, example="100")
Integer id){}



版权声明:本文为weixin_47356044原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。