<dependency>
<groupId>io.springfoxgroupId>
<artifactId>springfox-swagger2artifactId>
<version>2.9.2version>
dependency>
<dependency>
<groupId>io.springfoxgroupId>
<artifactId>springfox-swagger-uiartifactId>
<version>2.9.2version>
dependency>
@Configuration
@EnableSwagger2 //开启Swagger2
public class SwaggerConfig {
}
这里要注意测试网址:http://localhost:8080/swagger-ui.html
配置文件都在SwaggerConfig中:
//配置了Swagger的Docket的bean实例
@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo());
}
private ApiInfo apiInfo(){
Contact DEFAULT_CONTACT = new Contact("zc", "https://www.moyuzc.cn/", "moyu_zc@163.com");
return new ApiInfo(
"Swagger2 Test", //标题
"zc第一个测试", //描述
"1.0", //版本号
"https://www.moyuzc.cn/", //网址
DEFAULT_CONTACT, //上方设置的信息,名称、网址、邮箱地址
"Apache 2.0", //版权
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList());
}
进行测试:
创建两个配置接口,dev、test
application.properties
spring.profiles.active=dev
application-dev.properties
server.port=8081
application-test.properties
server.port=8082
设置要显示的Swagger环境
Profiles of = Profiles.of("dev","test");
environment.acceptsProfiles(of) 判断是否处于自己设定的环境
boolean flag = environment.acceptsProfiles(of); flag = environment.acceptsProfiles(of);
通过flag返回的boolean值判断能否进入
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.enable(flag)
.select()
.apis(RequestHandlerSelectors.basePackage("com.zc.controller"))
.build();
groupName(“zczc”) 使用这个方法,可以更改分组名称
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.groupName("zczc")
.enable(flag)
.select()
.apis(RequestHandlerSelectors.basePackage("com.zc.controller"))
.build();
另外增加A、B、C分组
@Bean
public Docket docket1(){
return new Docket(DocumentationType.SWAGGER_2)
.groupName("A");
}
@Bean
public Docket docket2(){
return new Docket(DocumentationType.SWAGGER_2)
.groupName("B");
}
@Bean
public Docket docket3(){
return new Docket(DocumentationType.SWAGGER_2)
.groupName("C");
}
创建实体类
public class User {
public String username;
public String password;
}
修改Controller类
@PostMapping("/user")
public User user(){
return new User();
}
因为在之前,SwaggerConfig类中已经扫描了Controller包,所以在分组正确的情况下,可以直接测试
实体类添加注释
@ApiModel("用户实体类")
public class User {
@ApiModelProperty("用户名")
public String username;
@ApiModelProperty("密码")
public String password;
}
Controller类加入注释
@ApiOperation("Hello2方法")
@GetMapping("/hello2")
public String hello2(@ApiParam("用户名") String username){
return "hello"+username;
}
个人博客为: MoYu’s HomePage MoYu’s Gitee Blog