springboot项目搭建之Swagger配置
pom.xml引入依赖
<!-- 接口文档 --> <!-- 引入swagger2的jar包 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.9.2</version> </dependency> <!--引入接口文档页面UI--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency>
注意:如果后面一系列都配置对了,项目不能运行,可能是Swagger 与 SpringBoot 版本不匹配出现的问题,可以降低SpringBoot 版本。
编写配置文件swaggerconfig
@Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .enable(true) // 是否禁用swagger .useDefaultResponseMessages(false) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.withClassAnnotation(Api.class)) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("swagger API文档") .description("测试接口文档") .version("1.0") .build(); } }
在Controller层相应接口加上Swagger注解
@RestController @Api(tags = "角色相关") @RequestMapping("/role") public class RoleController { /** * 服务对象 */ @Resource private RoleService roleService; /** * 通过主键查询单条数据 * * @param id 参数对象 * @return 单条数据 * roleId 参数对象 */ @ApiOperation("查询单条数据") @GetMapping("/id") public ResultInfo<Role> selectOne(@RequestParam("id") int id) { Role result = roleService.selectById(id); if(result != null){ return ResultInfoUtil.buildSuccess(result); } return ResultInfoUtil.buildError("查询失败"); } }
最后启动项目在浏览器输入地址即可
地址:
补充:在Apifox进行接口调试
配置好后就可以进行接口调试啦