1、pom.xml

<?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
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.trendmicro</groupId>
<artifactId>swagger</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>swagger</name>
<description>Demo project for Swagger</description>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<springfox.swagger.version>2.9.2</springfox.swagger.version>
<swagger-models.version>1.5.21</swagger-models.version>
<xiaoymin.swagger-ui.version>1.9.6</xiaoymin.swagger-ui.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<!-- ⽣成 Swagger ⽂档-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${springfox.swagger.version}</version>
<exclusions>
<exclusion> <groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-models</artifactId>
<version>${swagger-models.version}</version>
</dependency>
<!-- 添加 Springfox Swagger UI ⽀持 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>${springfox.swagger.version}</version>
</dependency>
<!-- 第三⽅swagger ui-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>${xiaoymin.swagger-ui.version}</version>
</dependency>
<!-- <dependency>-->
<!-- <groupId>com.github.xiaoymin</groupId>-->
<!-- <artifactId>knife4j-spring-boot-starter</artifactId>-->
<!-- <version>2.0.1</version>-->
<!-- </dependency>-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

2、配置⽂件

2.1 swagger可开关

application.properties中配置:

## 为true则开启swagger
swagger.enable=true

2.2 swagger配置

添加swagger2.properties配置⽂件 

############################### for swagger2
########################################
swagger.title=Test Rest API
swagger.description=Demo for swagger
swagger.termsOfServiceUrl=http://localhost:8080/swagger/doc.html
swagger.contact_name=xxx
swagger.contact_url=
swagger.contact_email=xxx@trendmicro.com
swagger.version=v1.0.0
swagger.license=
swagger.licenseUrl=
swagger.basePackage=com.trendmicro.swagger.rest

3、swagger配置 

3.1、SwaggerConfig.java 

package com.trendmicro.swagger.config;
import com.google.common.collect.Sets;
import com.trendmicro.swagger.config.annotation.IgnoreSwagger;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @Title: SwaggerConfig TODO
* @Description:
* @Program: swagger * @Author: Zhengya_Wu
* @Date: 2020-02-10 11:48
* @Version: 1.0
**/
@Configuration
@EnableSwagger2
@ConditionalOnExpression("${swagger.enable:true}")
public class SwaggerConfig {
@Resource
private SwaggerProperties properties;
/**
* @Description: 可以配置多个,⽤来⽣成不同在线⽂档
* @Param: []
* @return: springfox.documentation.spring.web.plugins.Docket
* @Author: Zhengya_Wu
* @Date: 2019/9/26 23:39
*/
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.tags(
new Tag("RestTestAPI | version 1.0", "The latest version
USES JSON interaction")
)

.apiInfo(apiInfoBuilder()).ignoredParameterTypes(IgnoreSwagger.class)
.useDefaultResponseMessages(false)
.groupName("RestTestApi")
.select()

.apis(RequestHandlerSelectors.basePackage(properties.getBasePackage()))
.paths(PathSelectors.any())
.build()
// .globalOperationParameters(getTokenPar())
// .securitySchemes(securitySchemes())
.securityContexts(securityContexts())
.consumes(Sets.newHashSet(MediaType.APPLICATION_JSON_VALUE))
;
}
private List getTokenPar() {
ParameterBuilder tokenPar = new ParameterBuilder();
List<Parameter> pars = new ArrayList<Parameter>();
tokenPar.name("Content-Type").defaultValue("application/json")
.description("Content-Type: application/json")
.modelRef(new
ModelRef("string")).parameterType("header").required(true).build();
pars.add(tokenPar.build());
return pars;
}
private ApiInfo apiInfoBuilder() {
return new ApiInfoBuilder()
.title(properties.getTitle())
.description(properties.getDescription())
.termsOfServiceUrl(properties.getTermsOfServiceUrl())
.contact(new Contact(properties.getContact_name(),
properties.getContact_url(), properties.getContact_email())) .version(properties.getVersion())
.license(properties.getLicense())
.licenseUrl(properties.getLicenseUrl())
.build();
}
private List<ApiKey> securitySchemes() {
return new ArrayList(Arrays.asList(new ApiKey("Authorization",
"Authorization", "header")));
}
private List<SecurityContext> securityContexts() {
return new ArrayList(
Arrays.asList(SecurityContext.builder()
.securityReferences(defaultAuth())
.forPaths(PathSelectors.regex("^(?!auth).*$"))
.build())
);
}
List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope("global",
"accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
return new ArrayList(
Arrays.asList(new SecurityReference("Authorization",
authorizationScopes)));
}
}

3.2、SwaggerProperties.java 

package com.trendmicro.swagger.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
/**
* @Title: SwaggerProperties TODO
* @Description:
* @Program: testrail-tools
* @Author: Zhengya_Wu
* @Date: 2019-10-15 15:36
* @Version: 1.0
**/
@Data
@Component
@ConfigurationProperties(prefix = "swagger")
@PropertySource(value = "classpath:/swagger2.properties", encoding = "utf-8")
public class SwaggerProperties {
private String title;
private String description;
private String termsOfServiceUrl;
private String contact_name;
private String contact_url; private String contact_email;
private String version;
private String license;
private String licenseUrl;
private String basePackage;
}

3.3、忽略参数注解 IgnoreSwagger.java 

package com.trendmicro.swagger.config.annotation;
import java.lang.annotation.*;
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface IgnoreSwagger {
}

4、使⽤ RestTestController.java 

package com.trendmicro.swagger.rest;
import com.trendmicro.swagger.entiry.Result;
import com.trendmicro.swagger.entiry.User;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;
/**
* @Title: RestController TODO
* @Description:
* @Program: swagger
* @Author: Zhengya_Wu
* @Date: 2020-02-10 11:11
* @Version: 1.0
**/
@Api(tags = "RestTestAPI | version 1.0", produces =
MediaType.APPLICATION_JSON_VALUE)
@Slf4j
@RestController
@RequestMapping("/rest/v1/")
public class RestTestController {
@ApiOperation(value = "user/{id}", notes = "Get user by user's id.")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "The ID of the user", required =
true, dataType = "int"),
}) @GetMapping(value = "user/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
public Result<User> getTest(@PathVariable("id") Integer id) {
log.info("[User] get user by id:{} ", id);
return
Result.success(User.builder().id(id).name("jeffrey_zhang").phone("188xxxxxxxxx").bui
ld());
}
@ApiOperation(value = "user", notes = "Update user's name or phone number by
user's id.")
@ApiResponses({
@ApiResponse(code = 200, message = "success"),
@ApiResponse(code = 400, message = "Request parameter error")
})
@PutMapping("user")
public Result updateTest(@RequestBody User user) {
log.info("[User] update user: {}", user.toString());
return Result.success();
}
@ApiOperation(value = "user/{id}", notes = "Delete user by user's id.")
@DeleteMapping("user/{id}")
public Result deleteTest(@PathVariable("id") Integer id) {
log.info("[User] delete user by id:{} ", id);
return Result.success();
}
@PostMapping("user")
public Result addTest(@RequestBody User user) {
log.info("[User] add user: {}", user.toString());
return Result.success();
}
@ApiIgnore
@GetMapping("test")
public Result test() {
log.info("test ignore.......");
return Result.success();
}
}

5、访问

原⽣: http://localhost:8080/swagger/swagger-ui.html

优化: http://localhost:8080/swagger/doc.html