引入依赖
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.9.2</version> </dependency>
swagger2相关配置
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 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; @Configuration @EnableSwagger2 public class Swagger2Configuration implements WebMvcConfigurer { //api接口包扫描路径 public static final String SWAGGER_SCAN_BASE_PACKAGE = "com.example.demo.controller"; public static final String VERSION = "1.0.0"; /** * 访问静态资源 */ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { /** * SpringBoot自动配置本身并不会把/swagger-ui.html * 这个路径映射到对应的目录META-INF/resources/下面 * 采用WebMvcConfigurerAdapter将swagger的静态文件进行发布; */ registry.addResourceHandler("swagger-ui.html") .addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/"); //将所有/static/** 访问都映射到classpath:/static/ 目录下 registry.addResourceHandler("/static/**").addResourceLocations( "classpath:/static/"); } @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .groupName("Xuym") .enable(true)//一定要开启 .select() .apis(RequestHandlerSelectors.basePackage(SWAGGER_SCAN_BASE_PACKAGE)) .paths(PathSelectors.any()) // 可以根据url路径设置哪些请求加入文档,忽略哪些请求 .build(); } private ApiInfo apiInfo() { // 配置作者信息 Contact contact = new Contact("诺言", "https://www.baidu.com", "*******@qq.com"); return new ApiInfoBuilder() .title("自己的Springboot项目") //设置文档的标题 .description("自己的Springboot项目,集成了Swagger2,属于一个小练习。") // 设置文档的描述 .version(VERSION) // 设置文档的版本信息-> 1.0.0 Version information .termsOfServiceUrl("http://www.baidu.com") // 设置文档的详细信息->1.3 License可自定义,最好放置部署地址 .build(); } }View Code
效果预览(稍微做了一下runner类的的配置,所以可以显示文档地址)
个人看法
1、随时生成文档,不需要额外的时间区编写测试文档
2、个人觉得从某些方面替代了postman:不用输入网址,不用输入参数名