springBoot中使用swagger
1.在maven中的pom文件中加入坐标
<!-- 引入swagger相关依赖 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
2.是用配置类对swagger进行配置
//告诉springboot开启对swagger2的支持
@EnableSwagger2
//配置类的注解
@Configuration
public class Swagger2Config {
/**
* 需要配置扫描controller的包路径
* 把swagger交给spring容器管理
*
* @Bean 基础声明
* Spring的@Bean注解用于告诉方法,产生一个Bean对象,然后这个Bean对象交给Spring管理。
* 产生这个Bean对象的方法Spring只会调用一次,随后这个Spring将会将这个Bean对象放在自己的IOC容器中。
* SpringIOC 容器管理一个或者多个bean,这些bean都需要在@Configuration注解下进行创建,
* 在一个方法上使用@Bean注解就表明这个方法需要交给Spring进行管理。
*/
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.briup.cms.web.controller"))
.paths(PathSelectors.any())
.build();
}
//swagger界面中显示的基本信息
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("看点咨询后台管理系统")
.description("欢迎访问briup官网,https://blog.csdn.net/jj89929665/article/details/109847968")
.termsOfServiceUrl("https://blog.csdn.net/jj89929665/article/details/109847968")
.version("1.0")
.build();
}
}
3.Controller中使用相关注解进行标识
//swagger中自动生成 API名字
@Api(tags = "测试模块")
//返回JSON格式 @RestController相当于@Controller+@ResponseBody
@RestController
public class HelloController {
//模块中的请求名字,和notes描述
@ApiOperation(value = "hello测试",notes = "第一个swagger测试程序")
@ApiImplicitParams({
@ApiImplicitParam(name = "name",value = "用户名",dataType = "String",required = true,paramType = "query",defaultValue = "tom"),
})
@GetMapping("/hello")
public Result hello(String name) {
if("tom".equals(name)) {
throw new RuntimeException("test...");
}
return Result.success("hello world!"+name);
}
}
4.在浏览器中启动
http://主机号:端口号/swagger-ui.html#/
比如
http://127.0.0.1:8989/swagger-ui.html#/
![](https://i-blog.csdnimg.cn/blog_migrate/fcfb7a8a8682c9a99c1c88a9d804a38f.png)
![](https://i-blog.csdnimg.cn/blog_migrate/f7c9e756b10ef20bd7d503a593e9d3a1.png)
![](https://i-blog.csdnimg.cn/blog_migrate/a9ee459f5441dacb507f8877531efd36.png)