一,spring-boot搭建的swaagger的api项目
二,如下代码
package com.nl.demo.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import springfox.documentation.builders.PathSelectors; import springfox.documentation.builders.RequestHandlerSelectors; import springfox.documentation.spi.DocumentationType; import springfox.documentation.spring.web.paths.RelativePathProvider; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2; import javax.servlet.ServletContext; @EnableSwagger2 public class SwaggerConfig { @Autowired /*ServletContext,是一个全局的储存信息的空间,服务器开始,其就存在,服务器关闭, 其才释放。request,一个用户可有多个;session,一个用户一个;而servletContext, 所有用户共用一个。所以,为了节省空间,提高效率,ServletContext中, 要放必须的、重要的、所有用户需要共享的线程又是安全的一些信息。*/ private ServletContext servletContext; @Bean public Docket docket() { return new Docket(DocumentationType.SWAGGER_2) .enable(true) .select() //接口的包名 .apis(RequestHandlerSelectors.basePackage("com.nl.testmybatis.controllers")) .paths(PathSelectors.any()) .build() .pathProvider(new RelativePathProvider(servletContext) { @Override public String getApplicationBasePath() { return "/"; } }); } }
package com.nl.demo.controllers; import io.swagger.annotations.ApiOperation; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.io.*; import java.text.SimpleDateFormat; import java.util.Date; @RestController @RequestMapping("test") public class TestController { @ApiOperation("getDate") @GetMapping("getDate") public String getDate() throws IOException { Date date=new Date(); SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); System.out.println( simpleDateFormat.format(date)); return simpleDateFormat.format(date); } }
package com.nl.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import springfox.documentation.swagger2.annotations.EnableSwagger2; @SpringBootApplication @EnableSwagger2 public class TestApplication { public static void main(String[] args){ SpringApplication.run(TestApplication.class); System.out.print("111111"); } }
application.yml
server: port: 8080 servlet: context-path: / ###swagger如下都是必须的配置, ###不然有可能访问http://localhost:8080/swagger-ui.html,会出现Whitelabel Error Page spring: mvc: static-path-pattern: /**
三,直接访问http://localhost:8080/swagger-ui.html就可以了
四,bug可能会出现swagger-ui.html出现Whitelabel Error Page,但是再配置里添加如下代码即可,原因是读取资源文件的路径不对
spring: mvc: static-path-pattern: /**