1、首先在SpringBoot官网创建一个带有web包的sb项目https://start.spring.io/
2、导入到idea或者eclipse,一下是我的项目结构(swagger与swagger_demo名字不一样而已)
3、在项目的pom.xml计入swagger的依赖
<!-- 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>
4、在sb项目启动类同级下创建Swagger2配置类
package com.example.swagger;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
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;
//swagger2的配置文件,在项目的启动类的同级文件建立
@Configuration
@EnableSwagger2
public class Swagger2 {
// swagger2的配置文件,这里可以配置swagger2的一些基本的内容,比如扫描的包等等
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
// 为当前包路径
.apis(RequestHandlerSelectors.basePackage("com.example.swagger.controller")).paths(PathSelectors.any())
.build();
}
// 构建 api文档的详细信息函数,注意这里的注解引用的是哪个
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
// 页面标题
.title("Spring Boot 测试使用 Swagger2 构建RESTful API")
// 创建人信息
.contact(new Contact("Gary", "https://blog.csdn.net/weixin_42334396/article/details/106172978", "1175171518@qq.com"))
// 版本号
.version("1.0")
// 描述
.description("API 描述")
.build();
}
}
5、properties文件里面设置启动swagger
#是否激活 swagger true or false
swagger.enable=true
6、SwaggerDemoController文件代码
package com.example.swagger.controller;
import com.example.swagger.pojo.Category;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 控制层 简单演示增删改查及分页
*/
@RestController
@RequestMapping("api")
@Api("swaggerDemoController相关的api")
public class SwaggerDemoController {
private static final Logger logger = LoggerFactory.getLogger(SwaggerDemoController.class);
//1.商品添加
//@PutMapping("add") 添加方法--restful风格
@PutMapping("add")
@ApiOperation(value = "商品新增")
//正常业务时, 需要在category类里或者server层进行事务控制,控制层一般不进行业务控制的。
//@Transactional(rollbackFor = Exception.class)
//@RequestParam 接收页面中的请求的参数
public Map<String, Object> addCategory(@RequestParam String name) {
List<Map> list = new ArrayList<>();
Map<String, Object> result = new HashMap<String, Object>();
Map<String, Object> categoryMap = new HashMap<>();
categoryMap.put("name", "牙膏");
categoryMap.put("stock", 99);
categoryMap.put("price", 29.0);
logger.info("开始新增某个商品信息");
result.put("respCode", "01");
result.put("respMsg", "新增成功!");
result.put("data", categoryMap);
return result;
}
//2.商品修改
//@PostMapping("update") 修改方法--restful风格
@PostMapping("update")
@ApiOperation(value = "商品修改", notes = "修改数据库中某个的商品信息")
//@RequestBody 接收页面中的请求的参数对象(适用于post请求)
//当入参为实体对象时,需要在方法上加@Valid或@Validated或者在参数前加@Valid或@Validated,或者在类上加@Validated
public Map<String, Object> updateCategory(@Validated @RequestBody Category category) {
Map<String, Object> result = new HashMap<String, Object>();
// Locale.Category categoryGet = categoryMapper.get(category.getId());
if (category == null || "".equals(category)) {
try {
throw new Exception("修改的该商品不存在!");
} catch (Exception e) {
e.printStackTrace();
}
result.put("respCode", "03");
result.put("respMsg", "修改的该商品不存在!");
result.put("data", category);
return result;
}
logger.info("开始修改某个商品信息");
result.put("respCode", "03");
result.put("respMsg", "修改成功!");
result.put("data", category);
return result;
}
//3.商品删除
//@DeleteMapping("/delete/{id}") 删除方法--restful风格
@DeleteMapping("/delete/{id}")
@ApiOperation(value = "根据id删除商品", notes = "商品删除")
@ApiImplicitParam(name = "id", value = "商品ID", paramType = "path", required = true, dataType = "Integer")
public Map<String, Object> deleteCategory(@PathVariable int id) throws Exception { //@PathVariable 获取/delete/{id}中id
Category category = new Category();
Map<String, Object> result = new HashMap<String, Object>();
if (category == null) {
try {
throw new Exception("用户ID:" + id + ",未找到");
} catch (Exception e) {
e.printStackTrace();
}
result.put("respCode", "02");
result.put("respMsg", "数据库无该商品信息,删除失败!");
result.put("data", category);
return result;
} else {
// categoryMapper.delete(id);
logger.info("开始删除某个商品信息");
result.put("respCode", "01");
result.put("respMsg", "删除成功!");
result.put("data", category);
return result;
}
}
//4.根据ID查询商品信息
//@GetMapping("") 查询方法--restful风格
@GetMapping("/get/{id}")
@ApiOperation(value = "根据id查询商品", notes = "查询数据库中某个的商品信息")
@ApiImplicitParam(name = "id", value = "商品ID", paramType = "path", required = true, dataType = "Integer")
public Map<String, Object> getCategory(@PathVariable int id) { //@PathVariable 获取/get/{id}中id
// Category category = categoryMapper.get(id);
Category category = new Category();
logger.info("开始查询某个商品信息");
Map<String, Object> result = new HashMap<String, Object>();
if (category == null) {
try {
throw new Exception("用户ID:" + id + ",未找到");
} catch (Exception e) {
e.printStackTrace();
}
result.put("respCode", "02");
result.put("respMsg", "数据库无该商品信息");
result.put("data", category);
return result;
} else {
result.put("respCode", "01");
result.put("respMsg", "查询成功!");
result.put("data", category);
return result;
}
}
//5.分页查询
//@GetMapping("") 查询方法--restful风格
@GetMapping("/page")
@ApiOperation(value = "商品查询(分页)")
public Map<String, Object> pageCategory(@RequestParam(value = "start", defaultValue = "0") int start, @RequestParam(value = "size", defaultValue = "5") int size) throws Exception {
//1. 在参数里接受当前是第几页 start ,以及每页显示多少条数据 size。 默认值分别是0和5。
//2. 根据start,size进行分页,并且设置id 倒排序
// PageHelper.startPage(start, size, "id desc");
//3. 因为PageHelper的作用,这里就会返回当前分页的集合了
// List<Category> cs = categoryMapper.findAll();
logger.info("开始分页查询商品信息");
//4. 根据返回的集合,创建PageInfo对象
// PageInfo<Category> page = new PageInfo<>(cs);
Map<String, Object> result = new HashMap<String, Object>();
result.put("respCode", "01");
result.put("respMsg", "成功");
// result.put("data", page);
return result;
}
}
7、pojo包的Category类
package com.example.swagger.pojo;
public class Category {
String id;
String name;
String level;
String parentId;
}
8、启动项目,访问http://localhost:8080/swagger-ui.html
完整代码包下载
https://download.csdn.net/download/weixin_42334396/13755117