Swagger配置
Swagger 通过配置 注解的方式完成接口文档的书写,并且在部署项目之后,通过 url 即可访问文档.
pom 文件配置
<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>
配置Swagger
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(getApiInfo())
.select()
// 配置扫描的 package
.apis(RequestHandlerSelectors.basePackage("com.yang.demo.controller"))
// 不能配置多个地址? [暂时未知]
//.apis(RequestHandlerSelectors.basePackage("com.yang.demo.bean"))
// 配置需要显示的地址
.paths(PathSelectors.any())
.build()
// 通过分组名 创建不同的 分组,添加多个 Docket Bean 对象
.groupName("主要分组")
.pathMapping("/");
}
@Bean
public Docket createRestApiOther(){
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(getApiInfoOther())
.select()
.apis(RequestHandlerSelectors.basePackage("com.yang.demo.bean"))
.paths(PathSelectors.any())
.build()
.groupName("次要分组")
.pathMapping("/");
}
private ApiInfo getApiInfo() {
return new ApiInfoBuilder()
.title("Swagger 标题")
.description("Swagger 内容说明")
.termsOfServiceUrl("链接地址")
// 用户信息
.contact(new Contact("KawYang", "https://blog.csdn.net/liang520521", "163@163.com"))
.version("V1.0")
.build();
}
private ApiInfo getApiInfoOther() {
return new ApiInfoBuilder()
.title("其他接口")
.description("其他接口说明")
.version("V1.0")
.build();
}
}
效果如下
接口配置
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@Api(tags = {"标签"})
public class MyController {
@RequestMapping(value = "/swagger", method = RequestMethod.GET)
public Object swagger(@ApiParam("name") String name) {
return name;
}
}
相关注解参考1
Swagger 访问 http://localhost:8080/swagger-ui.html
Swagger 地址4042
在 Swagger Configuration 中添加
/**
* 防止@EnableMvc把默认的静态资源路径覆盖了,手动设置的方式
*
* @param registry
*/
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
// 解决静态资源无法访问
registry.addResourceHandler("/**").addResourceLocations("classpath:/static/");
// 解决swagger无法访问
registry.addResourceHandler("/swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
// 解决swagger的js文件无法访问
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}