31.0、springboot-Swagger介绍以及集成
第一步:导入相关的swagger依赖:
<!--导入swagger的相关依赖-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
我们可以发现这并不是spring内部的依赖,所以我们还需要在配置类中配置一下
第二步:在config文件夹下创建一个配置类文件SwaggerConfig.java:
package com.hkl.config;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2 //开启Swagger2
public class SwaggerConfig {
}
第三步:测试运行http://localhost:8080/swagger-ui.html
能够进入这个swagger页面就算是测试运行成功
32.0、springboot-配置swagger信息
我们需要将swagger作为bean注入到容器当中
在SwaggerConfig.java文件中:
package com.hkl.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
@Configuration
@EnableSwagger2 //开启Swagger2
public class SwaggerConfig {
//配置了Swagger的Docket的bean实例
@Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo());
}
//配置Swagger信息=apiInfo
private ApiInfo apiInfo() {
//作者信息
Contact contact = new Contact("hkl","https://blog.csdn.net/m0_52433668","21123132@qq.com");
return new ApiInfo(
"hkl的swaggerAPI文档",
"天道酬勤",
"v1.0",
"https://blog.csdn.net/m0_52433668",
contact,
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList());
}
}
配置过后的swagger页面信息如下:
原码理解:
点击Docket进入可以看到有很多可以配置的属性,其中一个属性叫做ApiInfo,添加这个属性我们可以发现括号里需要一个ApiInfo类,所以我们在下面写了一个ApiInfo类把他注入进来。
点进Docket可以看到有一个DocumentationType类,再点进这个类就可以看到有一个SWAGGER_2()方法了。
ApiInfo里最下面有一个
static {
DEFAULT = new ApiInfo("Api Documentation", "Api Documentation", "1.0", "urn:tos", DEFAULT_CONTACT, "Apache 2.0", "http://www.apache.org/licenses/LICENSE-2.0", new ArrayList());
}
把他拿过来放到我们自己配置的ApiInfo方法里修改,这里只有一个地方会爆红,因为Contect需要有参数,我们只需要自己配置一下即可new Contect);