SpringBoot如何使用Swagger2构建API文档呢?
下文笔者讲述springboot中使用swagger2形成API文档的方法分享,如下所示
API文档的重要性
我们都知道API文档,可以非常直观的告诉使用者 如何使用相应的方法,那么有没有一种快捷的方法生成API文档呢? 下文呢笔者将讲述一个springboot中生成文档的利器swagger2
实现思路: 1.引入swagger2依赖 2.springBoot启动类中加入相应的注解 3.编写相应的测试类,即可查看swagger生成的api文档例:
Swagger2引入依赖
<!--swagger2依赖,构建API文档--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.2.2</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.2.2</version> </dependency>
设置启动类及swagger配置类的设置
注意事项: swagger配置类需和springboot处于同级或下级
/** * 启动类 */ @RequestMapping(value = "/") @RestController @SpringBootApplication @MapperScan(basePackages = "com.zzp.dao") @Configuration @EnableSwagger2 public class Round1Application { @RequestMapping(value = "/",method = RequestMethod.GET) public String helloWorld(){ return "Hello World"; } public static void main(String[] args) { SpringApplication.run(Round1Application.class, args); } @Bean public Docket createApi(){ return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select() .apis(RequestHandlerSelectors.basePackage("com.java265.controller")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo(){ return new ApiInfoBuilder() .title("API文档") .description("API使用即参数定义") .termsOfServiceUrl("http://www.java265.com") .contact("java265") .version("0.2") .build(); } }
当我们使用@Configuration注解后, Spring启动时加载配置 通过@EnableSwagger2开启Swagger apiInfo: 文档的一些基本配置信息 createApi: 用于指定扫描的包路径,然后形成文档,展示给用户 http://localhost:9090/swagger-ui.html例:
Controller中api的写法
在Controller中,我们只需使用 @ApiOperation注解 用于注释接口的基本信息 @ApiImplicitParam注解 用于设置入參信息
@RequestMapping("/user") @RestController public class UserController { @Autowired private UserService userService; /** * 添加用户 * @param tel 注册手机号 * @param pwd 设置密码 */ @ApiOperation(value = "创建用户",notes = "使用手机以及密码初始化用户信息") @ApiImplicitParams({ @ApiImplicitParam(name = "tel",value = "用户手机号",required = true,dataType = "String"), @ApiImplicitParam(name = "pwd",value = "用户初始密码",required = true,dataType = "String") }) @PostMapping("/createUser") public void createUser(@RequestParam("tel") String tel, @RequestParam("pwd") String pwd){ userService.createUser(tel,pwd); } /** * 添加用户2 * @param userInfo * @Valid添加表单验证,BindingResult获取验证结果 */ @ApiOperation(value = "创建用户V2版本",notes = "使用UserInfo对象初始化用户信息") @ApiImplicitParam(name = "userInfo",value = "用户对象",required = true,dataType = "UserInfo") @PostMapping("/createUser2") public String createUser2(@Valid UserInfo userInfo, BindingResult bindingResult){ if (bindingResult.hasErrors()){ return bindingResult.getFieldError().getDefaultMessage(); } userService.createUser(userInfo.getTel(),userInfo.getPassWord()); return "OK"; } /** * 更新用户信息 * @param user_id 用户ID * @param nickName 昵称 */ @PutMapping("/updateUser/{id}") public void updateUser(@PathVariable("id") String user_id, @RequestParam("nickName") String nickName){ userService.updateUser(user_id,nickName); } /** * 获取用户信息 * @param id 用户Id * @return */ @GetMapping("/getUser/{id}") public UserInfo getUser(@PathVariable("id") Integer id){ return userService.getUser(id); } /** * 删除用户 * @param id */ @DeleteMapping("/deleteUserByUserId/{id}") public void deleteUserByUserId(@PathVariable("id") Integer id){ userService.deleteUserByUserId(id); } /** * 使用@RequestBody获取参数,用map类型接收,再取出 * @param reqMap */ @PostMapping("/createUserByMap") public void createUserByMap(@RequestBody Map<String,Object> reqMap){ String tel = reqMap.get("tel").toString(); String pwd = reqMap.get("pwd").toString(); userService.createUser(tel,pwd); } } @RestController @RequestMapping("/xml") public class XMLController { @Autowired private XMLService service; @Autowired private ExceptionHandle handle; /** * 更新用户信息 * @param user_id 用户ID * @param nickName 昵称 */ @ApiOperation(value = "更新用户信息",notes = "更新用户昵称") @ApiImplicitParams({ @ApiImplicitParam(name = "id",value = "用户id",required = true,dataType = "String"), @ApiImplicitParam(name = "nickName",value = "用户昵称",required = true,dataType = "String") }) @PutMapping("/updateUser/{id}") public Result updateUser(@PathVariable("id") String user_id, @RequestParam("nickName") String nickName){ Result result = ResultUtil.success(); try { service.updateUser(user_id,nickName); }catch (Exception e){ result = handle.exceptionGet(e); } return result; } /** * 获取用户信息 * @param id 用户Id * @return */ @ApiOperation(value = "获取用户信息",notes = "返回用户信息") @ApiImplicitParam(name = "id",value = "用户id",required = true,dataType = "Integer",paramType = "path") @GetMapping("/getUser/{id}") public Result getUser(@PathVariable("id") Integer id){ Result result = ResultUtil.success(); try { result.setData(service.getUser(id)); }catch (Exception e){ result = handle.exceptionGet(e); } return result; } /** * 删除用户 * @param tel */ @ApiOperation(value = "删除用户",notes = "根据用户id删除用户") @ApiImplicitParam(name = "id",value = "用户id",required = true,dataType = "Integer") @DeleteMapping("/deleteUserByUserId/{tel}") public Result deleteUserByUserId(@PathVariable("tel") String tel){ Result result = ResultUtil.success(); try { UserInfo user = new UserInfo(); user.setTel(tel); service.deleteUserByUserId(user); }catch (Exception e){ result = handle.exceptionGet(e); } return result; } /** * 使用@RequestBody获取参数,用map类型接收,再取出 * @param reqMap */ @ApiOperation(value = "创建用户V3版本",notes = "返回用户信息") @ApiImplicitParam(name = "Map",value = "map集合",required = true,dataType = "Map") @PostMapping("/createUserByMap") public Result createUserByMap(@RequestBody Map<String,Object> reqMap){ Result result = ResultUtil.success(); try { service.createUser(reqMap); }catch (Exception e){ result = handle.exceptionGet(e); } return result; } }
Swagger2的优点
Swagger可避免接口文档的编写 直接由程序自动生成接口文档
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。