SpringBoot学习笔记——swagger-ui
swagger-ui用于给API添加文档,还支持API的请求调用,可以降低前后端联调的沟通成本
1.依赖
<!-- swagger2 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.8.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.8.0</version> </dependency>
2.配置swagger,注意修改basePackage成实际的包名
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.context.request.async.DeferredResult; import springfox.documentation.builders.ApiInfoBuilder; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.service.ApiInfo; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; @Configuration @EnableSwagger2 public class SwaggerConfig { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .genericModelSubstitutes(DeferredResult.class) .useDefaultResponseMessages(false) .forCodeGeneration(true) .apiInfo(apiInfo()) .pathMapping("/") // base,最终调用接口后会和paths拼接在一起 .select() .apis(RequestHandlerSelectors.basePackage("com.example.demo")) // 过滤的接口 .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("api文档") // 标题 .description("xxxx") // 描述 .termsOfServiceUrl("https://xxx.xxx.xxx") .version("1.0") .build(); } }
3.给controller添加 ApiOperation 注解
@ApiOperation(value = "hello接口", notes = "取得id,打印hello") @RequestMapping(path = "/hello/{id}", method = RequestMethod.GET) public ControllerResponseT hello(@ApiParam(name = "id", value = "id", required = true) @PathVariable("id") Integer id) { return ControllerResponseT.ofSuccess("hello: " + id); }
4.测试
如果在添加了统一的接口返回值配置之后出现swagger-ui.html 404,需要额外添加如下配置
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebAppConfig implements WebMvcConfigurer { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/**") .addResourceLocations("classpath:/public/"); registry.addResourceHandler("swagger-ui.html") .addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/"); } }
本文只发表于博客园和tonglin0325的博客,作者:tonglin0325,转载请注明原文链接:https://www.cnblogs.com/tonglin0325/p/5308786.html