一、Swagger使用步骤
导入依赖
<!-- 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>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
准备controller
@RestController
public class UserController {
@GetMapping("/user")
public String usermsg(){
return "user";
}
}
准备swagger的配置类
@Configuration
@EnableSwagger2
public class SwaggerConfig {
//配置返回的Docket对象
@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo());
}
private ApiInfo apiInfo(){
//contact :作者信息
Contact contact = new Contact("zgr", "www.baidu.com", "592488507@qq.com");
return new ApiInfo("SwaggerApi文档","第一个swagger文档","v1.0","自己的地址",contact,"Apache 2.0", "http://www.apache.org/licenses/LICENSE-2.0",new ArrayList<>());
}
}
访问页面 localhost:10086/swagger-ui.html
可以看到接口信息
二、Swagger简单配置
@Configuration
@EnableSwagger2
public class SwaggerConfig {
//配置返回的Docket对象
@Bean
public Docket docket(Environment environment){
//指定swagger当dev环境启用,test环境不启用
Profiles profiles = Profiles.of("dev");
//监听当前环境是否是dev
boolean b = environment.acceptsProfiles(profiles);
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.enable(b) //是否启用
.select()
//可以指定扫描的包
.apis(RequestHandlerSelectors.basePackage("com.example.swagger.controller"))
//指定url路径
.paths(PathSelectors.ant("/user/**"))
.build();
}
private ApiInfo apiInfo(){
//contact :作者信息
Contact contact = new Contact("zgr", "www.baidu.com", "592488507@qq.com");
return new ApiInfo("SwaggerApi文档","第一个swagger文档","v1.0","自己的地址",contact,
"Apache 2.0", "http://www.apache.org/licenses/LICENSE-2.0",new ArrayList<>());
}
}
多环境配置
spring:
profiles:
active: dev
---
spring:
jmx:
enabled: false
profiles: dev
server:
port: 10086
---
spring:
profiles: test
server:
port: 10087
swagger的分组操作
配置多个Docket对象
@Bean
public Docket docket1(){
return new Docket(DocumentationType.SWAGGER_2).groupName("一组");
}
@Bean
public Docket docket2(){
return new Docket(DocumentationType.SWAGGER_2).groupName("二组");
}
@Bean
public Docket docket3(){
return new Docket(DocumentationType.SWAGGER_2).groupName("三组");
}
三、Swagger注解配置
@ApiModel 对实体类说明
@ApiModelProperty 对实体类属性说明
@ApiModel("用户类")
public class User {
@ApiModelProperty("用户名")
private String username;
@ApiModelProperty("密码")
private Integer age;
}
Get请求传参 get请求需要指定@RequestParam
但使用@RequestParam必须得传参数,但有时有的参数我们不一定必须要传
可以使用@ApiImplicitParam注解,其中required属性默认为false