1.新建SpringBoot项目,配置pom文件
<!-- swagger api 依赖开始-->
<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>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.0</version>
</dependency>
<!-- swagger api 依赖结束-->
2.添加Swagger配置类 SwaggerConfig.java
package com.qiankai.demoswagger.config;
@Configuration
@EnableWebMvc
@EnableSwagger2
@ComponentScan("com.qiankai.demoswagger.controller")
public class SwaggerConfig {
@Bean
public Docket customDocket(){
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo());
}
private ApiInfo apiInfo(){
Contact contact = new Contact("QL", "http://qiankyle.cn", "qiankaicode@163.com");
return new ApiInfoBuilder()
.title("QK项目API接口")
.description("这是API接口 description")
.contact(contact)
.version("1.1.0")
.build();
}
}
3.WebMvc配置
package com.qiankai.demoswagger.config;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
4.Controller
package com.qiankai.demoswagger.controller;
@RestController
@Api(value = "用户模块",description = "用户模块的接口信息")
public class UserController {
//模拟数据库
private static List<User> users = new ArrayList<>();
static {
users.add(new User("zsname", "zspass"));
users.add(new User("lsname", "lspass"));
}
// 获取用户集合
@GetMapping("/users")
@ApiOperation(value = "获取用户列表",notes = "获取所有用户的列表")
public Object getUsers() {
Map<String, Object> map = new HashMap<>();
map.put("users", users);
return map;
}
@ApiOperation(value = "获取单个用户",notes = "根据id查询某个用户的信息")
@ApiImplicitParam(value = "用户的id",paramType = "path")
@GetMapping("/user/{id}")
public User getUserById(@PathVariable("id") int id) {
return users.get(id);
}
@ApiOperation(value = "添加用户",notes = "根据传入的用户信息添加用户")
@ApiImplicitParam(value = "用户对象",paramType = "query")
@PostMapping("/user")
public Object add(User user) {
return users.add(user);
}
@ApiOperation(value = "删除用户",notes = "根据传入的id删除用户")
@ApiImplicitParam(value = "用户的id",paramType = "path")
@DeleteMapping("/user/{id}")
public Object delete(@PathVariable("id") int id) {
return users.remove(id);
}
}
5.启动类加上@EnableWebMvc