Spring Boot+Swagger2

Swagger使用

1. Swagger是什么?

官方说法:Swagger是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新。文件的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步。

使用Swagger2有助于我们编写一份详细的RESTful业务接口文档,过去经常会使用Word或者Excel,但是接口非常多,细节又复杂,如果由程序员高质量的输出一个文档,经常耗时长而且效果也不好。Swagger2能将代码和注释说明很好结合在一块。既减轻了研发人员的负担,又能输出高质量的文档。


2. spring boot 集成 Swagger

spring-boot系统集成swagger需要进行如下操作:

  1. 添加maven依赖,需要在系统的pom中添加如下依赖:

  2. <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>
  3. 2.添加swagger配置文件,配置文件如下: 

@Configuration  //注解,让Spring来加载该类配置
public class Swagger2Config {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())//添加api信息
                .select()   // 选择那些路径和api会生成document
                .apis(RequestHandlerSelectors.basePackage("com.mxyinhao.broker"))// 对api进行监控(填写controller目录)
                .paths(PathSelectors.any())// 对所有路径进行监控
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("测试接口")
                .termsOfServiceUrl("http://www.mxyinhao.com/")
                .contact("作者名")
                .version("0.0.1-SNAPSHOT")
                .build();
    }
}

  3.入口处添加标签

@EnableAutoConfiguration//开启spring自动配置功能
@SpringBootApplication
@EnableSwagger2//注解来启用Swagger2。
public class BrokerPortalApplication {
    public static void main(String[] args) {
        SpringApplication.run(BrokerPortalApplication.class, args);
    }
}
4.网页访问
http://127.0.0.1:8080/swagger-ui.html#!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值