在springboot中使用swaager-ui
1.引入jar包
<!-- 添加swagger2 --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.7.0</version> </dependency> <!-- swagger2-UI --> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.7.0</version> </dependency>
2.编写配置类
Swagger.java
package com.ebda.config.swagger; import org.springframework.beans.factory.annotation.Autowired; 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.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; /** * Swagger 配置文件 * */ @Configuration @EnableSwagger2 //启动swagger注解 启动服务,浏览器输入"http://服务名:8080/swagger-ui.html" public class Swagger { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) // 用来创建该API的基本信息,展示在文档的页面中(自定义展示的信息) .apiInfo(apiInfo()) // 设置哪些接口暴露给Swagger展示 .select() // 扫描所有有注解的api,用这种方式更灵活 .apis(RequestHandlerSelectors.basePackage("com.ebda")) // 扫描指定包中的swagger注解 // 扫描所有 .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() //设置标题 .title("ebda文档") //描述 .description("swagger-ui测试") //服务条款URL .termsOfServiceUrl("") //版本 .version("版本号:1.0") .build(); } }
3.访问http://localhost:8080/swagger-ui.html ,结果404
4.查找原因,在网上找到两种方式
第一种:在配置文件application.properties中添加配置
spring.mvc.static-path-pattern=/** spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/
主要是需要这个配置来访问到jar中的html文件 classpath:/META-INF/resources/
第二种:添加如下代码
package com.ebda.config.swagger; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration public class WebMvcConfig extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("swagger-ui.html") .addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/"); } }
重启服务就可以访问到了