SpringBoot结合Swagger2自动生成api文档
首先在pom.xml中添加如下依赖,其它web,lombok等依赖自行添加
<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>
SwaggerConfig.java是swagger2的配置类
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("cn.niit.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Spring Boot中使用Swagger2")
.description("首次尝试自动生成api文档为后期的前后端分离开发做准备")
.termsOfServiceUrl("https://www.jianshu.com/u/2f60beddf923")
.contact("WEN")
.version("1.0")
.build();
}
}
实体类User.java
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
public User(String userName, String password) {
this.userName = userName;
this.password = password;
}
private Integer id;
private String userName;
private String password;
}
新建一个控制类UserController.java,类下有个方法getAllUser
@RestController
@Api(description = "用户管理")
@RequestMapping(value = "/hello",produces = APPLICATION_JSON_VALUE)
public class UserController {
List<User>lists=new ArrayList<>();
@GetMapping(value ="getAllUser" )
@ApiOperation(value = "用户列表",notes = "查询所有已注册过的用户详细信息")
public List<User> getAllUser()
{
lists.add(new User("wen","999"));
lists.add(new User(2,"qian","666"));
return lists;
}
}
点击localhost:8888/swagger-ui.html(我在application.propertise中的server.port=8888)
在类中再添加一个方法addUser
@PostMapping(value = "addUser")
public User addUser(User user)
{
return user;
}
实体类User.java的属性上添加如下注解
@ApiModelProperty(value = "用户ID")
private Integer id;
@ApiModelProperty(value = "用户名")
private String userName;
@ApiModelProperty(value = "密码")
private String password;
创建用户时有些字段我们并不需要,可以加入如下注解
@ApiModelProperty(hidden = true)
在类中再添加一个根据用户id查询用户的方法
@GetMapping(value = "getUserById/{id}")
public User getUserById(@ApiParam(value = "用户ID")@PathVariable(value = "id")String id)
{
return new User(id,"步惊云","passwordjava");
}
汉化成中文文档
在swagger相关的jar包
把META-INF这个包复制到你当前项目的resources目录下
这些是关键,剩下多余的包可自行删除
在swagger-ui.html的部分添加如下代码
<!--国际化操作:选择中文版 -->
<script src='webjars/springfox-swagger-ui/lang/translator.js' type='text/javascript'></script>
<script src='webjars/springfox-swagger-ui/lang/zh-cn.js' type='text/javascript'></script>
汉化完成,我们也可以在zh_cn.js中自定义中文名称
另一种生成文档的方式请参见