1. 引入依赖
<!--swagger2依赖-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
2. 添加配置
创建于主程序类同级的Swagger2 类
内容如下
@Configuration //标记配置类
@EnableSwagger2 //开启在线接口文档
public class Swagger2 {
@Bean
public Docket createRestfulApi() {//api文档实例
return new Docket(DocumentationType.SWAGGER_2)//文档类型:DocumentationType.SWAGGER_2
.apiInfo(apiInfo())//api信息
.select()//构建api选择器
.apis(RequestHandlerSelectors.basePackage("com.example.demo.Controller"))//api选择器选择api的包
.paths(PathSelectors.any())//api选择器选择包路径下任何api显示在文档中
.build();//创建文档
}
private ApiInfo apiInfo() {//接口的相关信息
return new ApiInfoBuilder()
//页面标题
.title("Spring Boot中使用Swagger2构建RESTful接口")
//描述
.description("接口描述")
.termsOfServiceUrl("termsOfServiceUrl")
//创建人
.contact(new Contact("Mr.sun", null, null))
//版本号
.version("1.0")
.build();
}
}
注意更改与自己项目相符合的api路径
下面的ApiInfo显示效果如下
3. 编写接口文档
@Api(tags="用户信息管理系统",value = "用户信息管理")
@Controller
@RequestMapping(value = "/user")
public class UserController {
@Autowired
private UserService userService;
@ResponseBody
@RequestMapping(value = "/select",method = RequestMethod.GET)
@ApiOperation(value = "查询所有用户",notes = "用户信息")
public Object selectAllUser(){
return userService.findAllUser();
}
@ResponseBody
@RequestMapping(value = "/selectByid",method = RequestMethod.POST)
@ApiOperation(value = "根据id查询使用者信息",notes = "id为string类型")
@ApiImplicitParam(name = "user", value = "单个用户信息", dataType = "User")
public User selectByid(String id){
return userService.selectByid(id);
}
}
以上配置显示效果如下。
扫描二维码关注公众号,回复:
3397318 查看本文章
可以根据自己的需要增加 具体说明如下
//@Api:用在请求的类上,表示对类的说明
// tags="说明该类的作用,可以在UI界面上看到的注解"
// value="该参数没什么意义,在UI界面上也看到,所以不需要配置"
//
//@ApiOperation:用在请求的方法上,说明方法的用途、作用
// value="说明方法的用途、作用"
// notes="方法的备注说明"
//
//@ApiImplicitParams:用在请求的方法上,表示一组参数说明
//@ApiImplicitParam:用在@ApiImplicitParams注解中,指定一个请求参数的各个方面
// name:参数名
// value:参数的汉字说明、解释
// required:参数是否必须传
// paramType:参数放在哪个地方
// · header --> 请求参数的获取:@RequestHeader
// · query --> 请求参数的获取:@RequestParam
// · path(用于restful接口)--> 请求参数的获取:@PathVariable
// · body(不常用)
// · form(不常用)
// dataType:参数类型,默认String,其它值dataType="Integer"
// defaultValue:参数的默认值
//
//@ApiResponses:用在请求的方法上,表示一组响应
//@ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息
// code:数字,例如400
// message:信息,例如"请求参数没填好"
// response:抛出异常的类
//
//@ApiModel:用于响应类上,表示一个返回响应数据的信息
// (这种一般用在post创建的时候,使用@RequestBody这样的场景,
// 请求参数无法使用@ApiImplicitParam注解进行描述的时候)
//@ApiModelProperty:用在属性上,描述响应类的属性