Spring Boot集成Swagger

  1. 添加Maven坐标
<!-- 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>
  1. 编写一个配置类
@Configuration //配置类
@EnableSwagger2// 开启Swagger2的自动配置
public class SwaggerConfig {
	@Bean
	public Docket docket() {
		// 设置要启用Swagger的环境
		Profiles profiles = Profiles.of("dev", "test");
		// 判断当前是否处于该环境,通过 enable() 接收此参数判断是否要启用Swagger
		boolean flag = environment.acceptsProfiles(profiles);
		
		return new Docket(DocumentationType.SWAGGER_2)
			.groupName("group1")// 设置分组,方便多人协作开发
			.apiInfo(apiInfo())
			.enable(flag)
			.select()// 通过.select()方法,去配置扫描接口,RequestHandlerSelectors配置如何扫描接口 
			.apis(RequestHandlerSelectors.basePackage("com.example.controller"))// basePackage 扫描指定包路径下的接口。其他扫描方式可以点开RequestHandlerSelectors的源码查看
			.build();
	}
	
	//配置文档信息
	private ApiInfo apiInfo() {
		Contact contact = new Contact("联系人名字", "http://xxx.xxx.com/联系人访问链接", "联系人邮箱");
		return new ApiInfo(
			// 标题
			"Swagger学习", 
			// 描述
			"学习演示如何配置Swagger", 
			// 版本
			"v1.0", 
			 // 组织链接
			"http://terms.service.url/组织链接",
			// 联系人信息
			contact, 
			// 许可
"			Apach 2.0 许可", 
			// 许可连接
			"许可链接", 
			// 扩展
			new ArrayList<>()
		);
	}
}
  1. 配置实体类
@ApiModel("用户实体")
public class User {

	@ApiModelProperty("用户名")
	public String username;
	
	@ApiModelProperty("密码")
	public String password;
	
}
  1. 常用注解
  • @ApiOperation("xxx接口说明"):作用在接口方法上
  • @ApiModel("xxxPOJO说明"):作用在实体类上
  • @ApiModelProperty(value = "xxx属性说明", hidden = true):作用在实体类的属性上,hidden设置为true可以隐藏该属性
  • @ApiParam("xxx参数说明"):作用在接口方法的参数上
  1. 访问测试

    http://localhost:8080/swagger-ui.html

posted @ 2021-05-30 09:12  Java程序员的进阶之路  阅读(67)  评论(0编辑  收藏  举报