创建springboot项目
创建一个Spring Boot项目,加入Swagger2相关的依赖,完整的依赖如下
<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>
配置Swagger2
/**
* @author fengjunhong
* @date 2020/3/18 16:10
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.pathMapping("/")
.select()
.apis(RequestHandlerSelectors.basePackage("com.qskj.swagger2")) //换成自己的包
.paths(PathSelectors.any())
.build().apiInfo(new ApiInfoBuilder()
.title("SpringBoot整合Swagger")
.description("SpringBoot整合Swagger,详细信息......")
.version("9.0")
.license("The Apache License")
.contact(new Contact("诸葛大力","www.baidu.com","zgdl@qq.com"))
.licenseUrl("http://www.baidu.com")
.build());
}
}
启动项目
此时启动项目,输入http://localhost:8080/swagger-ui.html,能够看到如下页面,说明已经配置成功了:
创建接口
/**
* @author fengjunhong
* @date 2020/3/18 16:25
*/
@RestController
@Api(tags = "用户管理相关接口")
@RequestMapping("/user")
public class UserController {
@GetMapping("/")
@ApiOperation("根据id查询用户的接口")
@ApiImplicitParam(name = "id", value = "用户id", defaultValue = "99", required = true)
public User getUserById(@PathVariable Integer id) {
User user = new User();
user.setId(id);
return user;
}
@PutMapping("/{id}")
@ApiOperation("根据id更新用户的接口")
public User updateUserById(@RequestBody User user) {
return user;
}
}
注解讲解
注解 | 说明 |
---|---|
@Api | 标记当前Controller的功能 |
@ApiOperation | 标记一个方法的作用 |
@ApiImplicitParam | 用来描述一个参数,可以配置参数的中文含义,也可以给参数设置默认值,这样在接口测试的时候可以避免手动输入 |
说明:如果有多个参数,则需要使用多个@ApiImplicitParam注解来描述,多个@ApiImplicitParam注解需要放在一个@ApiImplicitParams注解中。
举个栗子:
@ApiImplicitParams({
@ApiImplicitParam(name = "username", value = "用户名", defaultValue = "李四"),
@ApiImplicitParam(name = "address", value = "用户地址", defaultValue = "深圳", required = true)
}
最终效果
好了,经过如上配置之后,接下来,刷新刚刚打开的页面,可以看到如下效果:
在Security中的配置
如果我们的Spring Boot项目中集成了Spring Security,那么如果不做额外配置,Swagger2文档可能会被拦截,此时只需要在Spring Security的配置类中重写configure方法,添加如下过滤即可
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers("/swagger-ui.html")
.antMatchers("/v2/**")
.antMatchers("/swagger-resources/**");
}