1.pom添加依赖
<!-- swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.5.0</version>
</dependency>
<!-- swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.5.0</version>
</dependency>
2.创建配置类(与springboot启动类平级)
package com.passingly;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig
{
@Bean
public Docket api()
{
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
.select()
// 自行修改为自己的包路径
.apis(RequestHandlerSelectors
.basePackage("com.passingly.web.controller"))
.paths(PathSelectors.any())
.build();
}
// 构建 api文档的详细信息函数,注意这里的注解引用的是哪个
private ApiInfo apiInfo()
{
return new ApiInfoBuilder()
// 页面标题
.title("***系统-api文档")
// 创建人
.contact(new Contact("gulang", "http://www.baidu.com", ""))
// 版本号
.version("1.0")
// 描述
.description("API 描述")
.build();
}
}
3.在 controller类添加swagger2(API)注解
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.passingly.model.entity.UserEntity;
import com.passingly.model.req.UserReq;
import com.passingly.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@Api("用户测试")
@RestController
@RequestMapping(value = "/user")
public class UserController
{
@Autowired
private UserService userService;
@ApiOperation(value = "查询用户信息", notes = "查询数据库用户信息")
@RequestMapping("/list")
public List<UserEntity> list(UserReq userReq)
{
return userService.list(userReq);
}
}
至此swagger配置完毕,启动项目打开网址
- localhost:8080/swagger-ui.html
会看到同一个存在多个请求,需要在controller的RequestMapping添加请求方式即可
@RequestMapping(value = "/user", method = {RequestMethod.POST,RequestMethod.GET})
启动后发现请求参数看不到
需要在controller入参的位置添加注解@RequestBody并在实体类中添加解释注解
重启系统后点击入参即可,很方便
- 在这里转载swagger的一些常用注解
https://blog.csdn.net/wyb880501/article/details/79576784