首页 > 其他分享 >Swagger快速使用

Swagger快速使用

时间:2023-01-18 19:08:50浏览次数:40  
标签:return 快速 扫描 使用 new Swagger Docket public


Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。

pom

<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>

SwaggerConfig

配置扫描指定的接口

@Configuration
@EnableSwagger2
public class SwaggerConfig {

// 配置多个Swagger的bean,可以分组显示
@Bean
public Docket docket1(){
return new Docket(DocumentationType.SWAGGER_2).groupName("A");
}
@Bean
public Docket docket2(){
return new Docket(DocumentationType.SWAGGER_2).groupName("B");
}

// 配置了Swagger的Docket的bean实例
@Bean
public Docket docket(Environment environment) {
// 设置要显示的Swagger环境
Profiles profiles = Profiles.of("dev");
// 通过environment.acceptsProfiles判断是否处在自己设定的环境当中
boolean b = environment.acceptsProfiles(profiles);

return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
// 是否启用Swagger
.enable(b)
// RequestHandlerSelectors配置要扫描接口的方式
// withClassAnnotation 扫描类上的注解,参数是一个注解的反射对象,withMethodAnnotation 扫描方法上的注解
// basePackage指定要扫描的包,any() 扫描全部,none() 不扫描
.select().apis(RequestHandlerSelectors.basePackage("com.example.car.controller"))
// 过滤扫描路径,只扫描路径为 /car/xxx 的接口
.paths(PathSelectors.ant("/car/**"))
.build();
}

// 配置Swagger信息==apiInfo,源码只有构造没有set方法,只能通过这种方式绑定
private ApiInfo apiInfo() {
// 作者信息
Contact concat = new Contact("author", "http://baidu.com", "[email protected]");

return new ApiInfo(
"author的Swagger文档",
"描述内容",
"v1.0",
"http://baidu.com",
concat,
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList());
}
}

扫描实体类

只要接口的返回值中存在实体类,就会被Swagger扫描

@ApiModel("统一格式返回结果")
public class Result {
@ApiModelProperty("状态码")
private int code;
@ApiModelProperty("错误信息")
private String msg;
@ApiModelProperty("返回结果")
private Object data;

public Result(Object data){
this.data = data;
}
}

接口注释

@ApiOperation("用户登录")
@RequestMapping(value = "/login",method = RequestMethod.POST)
public String Login(@ApiParam("用户名") String username, @ApiParam("密码") String pwd){
return "login success";
}

注:在项目正式发布运行的时候,记得关闭Swagger


标签:return,快速,扫描,使用,new,Swagger,Docket,public
From: https://blog.51cto.com/u_14452299/6019400

相关文章