温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何使用Spring Boot集成Swagger

发布时间:2021-10-13 10:08:31 来源:亿速云 阅读:120 作者:iii 栏目:编程语言

这篇文章主要讲解了“如何使用Spring Boot集成Swagger”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“如何使用Spring Boot集成Swagger”吧!

如何使用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参数说明"):作用在接口方法的参数上

感谢各位的阅读,以上就是“如何使用Spring Boot集成Swagger”的内容了,经过本文的学习后,相信大家对如何使用Spring Boot集成Swagger这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI