1.导入依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-boot-starter</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>3.0.2</version>
</dependency>
2.书写配置类
package net.royalreairman.synth.commons.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.Contact;
import springfox.documentation.service.SecurityScheme;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import java.util.Collections;
import java.util.List;
@Profile({"local", "dev"})
@EnableOpenApi
@Configuration
public class SwaggerConfig {
@Bean
public Docket desertsApi() {
return new Docket(DocumentationType.OAS_30)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("net.royalreairman.synth"))
.paths(PathSelectors.any())
.build()
.groupName("desertsGroup")
// 设置安全方案
.securitySchemes(security())
.enable(true);
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Swagger3接口文档")
.description("文档描述信息")
.contact(new Contact("royal", "#", ""))
.version("1.0")
.build();
}
private List<SecurityScheme> security() {
return Collections.singletonList(new ApiKey("Access-Token", "Access-Token", "header"));
}
}
3.在启动类加上 接口信息 ,方便后期找到swagger地址
private static final Logger logger = LoggerFactory.getLogger(SystemApplication.class);
public static void main(String[] args) {
// SpringApplication.run(SystemApplication.class, args);
ConfigurableApplicationContext applicationContext = SpringApplication.run(SystemApplication.class,args);
ConfigurableEnvironment environment = applicationContext.getEnvironment();
String serverPort = environment.getProperty("server.port");
String url = "http://127.0.0.1:" + serverPort + "/doc.html";
logger.info("项目启动成功,knife4jsSwagger访问地址是:{}", url);
url = "http://127.0.0.1:" + serverPort + "/swagger-ui/index.html#";
logger.info("项目启动成功,swagger访问地址是:{}", url);
}
4,启动项目