在此前写接口的时候用的都是postman,包括前端也是通过postman进行查看接口的相关信息的,听说Swagger还挺好用的,可以自动生成接口文档,我就与项目整合在一起,发现还行(应前端的要求哈哈哈)
接下来我来记录一下我项目整合的过程吧!我是SpringBoot整合Swagger2
第一步导入相关的包
<!-- Swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.8.0</version>
</dependency>
<!-- END Swagger -->
第二步:编写配置类
@Configuration
@EnableSwagger2
public class Swagger2Config {
@Bean
public Docket createRestApi(Environment environment){
//设置要显示swagger的环境
Profiles profile = Profiles.of("dev");
//获取项目环境(判断是否处在自己设定的环境中)
boolean flag = environment.acceptsProfiles(profile);
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.enable(flag)//是否启动Swagger,如果是false,则Swagger不能在浏览器中访问
.select()
.apis(RequestHandlerSelectors.basePackage("com.macro.mall.controller"))//RequestHandlerSelectors:配置要扫描接口的方式:此处是基于指定包
.paths(PathSelectors.any())//过滤什么路径
.build()
.securitySchemes(securitySchemes())
.securityContexts(securityContexts());
}
/**
*
* <pre>
* 我们可以配置多个bean,那么在显示地时候我们可以对接口进行分组
* 尤其是多人开发的时候,根据每个人写的接口进行分组,比较好管理
* <pre>
* @author hejianfeng
* @date 2020/2/29
* @param
* @return springfox.documentation.spring.web.plugins.Docket
* <pre>
* 修改记录
* 版本号 修订日期 修改人 bug编号 修改内容
* 1.0.0 2020/2/29 何建锋 新建
* </pre>
*/
@Bean
public Docket docketOne(){
return new Docket(DocumentationType.SWAGGER_2).groupName("hejianfeng");
}
//只希望在生产环境中使用,发布的时候不使用
//
/**
*
* <pre>
* 配置swagger信息
* <pre>
* @author 何建锋
* @date 2020/2/29
* @param
* @return springfox.documentation.service.ApiInfo
* <pre>
* 修改记录
* 版本号 修订日期 修改人 bug编号 修改内容
* 1.0.0 2020/2/29 何建锋 新建
* </pre>
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("我的API文档")
.description("mall后台模块")
.contact("macro")
.version("1.0")
.build();
}
private List<ApiKey> securitySchemes() {
//设置请求头信息
List<ApiKey> result = new ArrayList<>();
ApiKey apiKey = new ApiKey("Authorization", "Authorization", "header");
result.add(apiKey);
return result;
}
private List<SecurityContext> securityContexts() {
//设置需要登录认证的路径
List<SecurityContext> result = new ArrayList<>();
result.add(getContextByPath("/brand/.*"));
result.add(getContextByPath("/product/.*"));
result.add(getContextByPath("/productCategory/.*"));
return result;
}
private SecurityContext getContextByPath(String pathRegex){
return SecurityContext.builder()
.securityReferences(defaultAuth())
.forPaths(PathSelectors.regex(pathRegex))
.build();
}
private List<SecurityReference> defaultAuth() {
List<SecurityReference> result = new ArrayList<>();
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
result.add(new SecurityReference("Authorization", authorizationScopes));
return result;
}
}
第三步:在controller类中添加注解使用