swagger2的使用

前后端分离项目中,对于API的管理一直很头疼,swagger2即可以解决这个问题!

1)引入依赖:

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.7.0</version>
</dependency>

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.7.0</version>
</dependency>

2)***Swagger配置类

@Configuration
public class Swagger2 {

    @Value("${swagger2.enable}")
    private boolean enable;

    /**
    * 在Docket创建中,通过groupName进行分组,paths属性进行过滤,apis属性可以设置扫描包,或者通                                
    * 过注解的方式标识;通过enable属性,可以在application-{profile}.properties文件中设置相                    
    * 应值,主要用于控制生产环境不生成接口文档
    */
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
	    .apiInfo(apiInfo())
            .select()
            // .apis(RequestHandlerSelectors.basePackage("com.xxx.Controller")) 只扫描Controller
            // 方法上有ApiOperation注解的才被扫描
            .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
            .paths(PathSelectors.any())
            // .paths(PathSelectors.regex("/user.*")) 可以使用正则过滤
            .enable(enable)
            .build();
    }
    
    //包括 标题、描述、服务网址、联系人、版本等信息
    private ApiInfo apiInfo() {
	return new ApiInfoBuilder()
            .title("XXX系统平台API接口文档")
            .description("接口文档")
            .termsOfServiceUrl("")
            .version("1.0")
            .build();
	}
}

3)spring boot主启动类加上@EnableSwagger2注解

// Application.class加上@EnableSwagger2注解表示开启Swagger
@SpringBootApplication
@EnableSwagger2
public class SpringbootSwagger2Application {
    public static void main(String[] args) {
	SpringApplication.run(SpringbootSwagger2Application.class, args);
    }
}

4)restful接口

/**
* 根据ID和name查询用户
* @param id,name
* @return
*/
@ApiOperation(value="获取用户详细信息", notes="根据url的id来获取用户详细信息")
@ApiImplicitParams({
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Integer", paramType = "path"),
    @ApiImplicitParam(name = "name", value = "用户名", required = true, dataType = "String", paramType = "path")
})
@GetMapping("user/{id}/{name}")
public User getUserByIdAndName (@PathVariable(value = "id") Integer id, @PathVariable(value = "name") String name){
    // xxx
}

项目启动后,访问路径为:IP:端口 + swagger-ui.html

同时,开放以下几个路径不做拦截:

/swagger-ui.html

/swagger-resources

/swagger-resources/configuration/security

/swagger-resources/configuration/ui

/v2/api-docs

/webjars/springfox-swagger-ui/**

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值