一、加入swagger相關依賴html
pom.xml文件配置java
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.zhui</groupId> <artifactId>java-demo</artifactId> <version>1.0-SNAPSHOT</version> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.7.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.7.0</version> </dependency> </dependencies> </project>
二、編寫Swagger配置類web
package com.zhui.config; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; 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 public class SwaggerConfig { private Logger logger = LoggerFactory.getLogger(SwaggerConfig.class); @Value("${swagger.enable}") private boolean isSwaggerEnable; @Bean public Docket createRestApi() { logger.info("SwaggerConfig createRestApi 構建REST API"); logger.info("Swagger啓用標誌:{}",isSwaggerEnable); return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.zhui.cotrollers")) //Controller所在包(必須新建包) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { logger.info("SwaggerConfig apiInfo API信息"); return new ApiInfoBuilder() .title("java-demo構建api文檔") //標題 .description("swagger description") //描述 .version("1.0") .build(); } }
三、swagger是否開啓最好配置在配置文件中(application.yml)spring
server: port: 9001 #swagger swagger: enable: true
四、訪問swagger(http://localhost:9001/swagger-ui.html)apache