准备:pom文件中增加Swagger2依赖
<!--引入swagger插件 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.1</version>
</dependency>
<!--引入swaggerUI包 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.1</version>
</dependency>
编写配置类:
package *;
import java.util.ArrayList;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
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;
@Configuration //设置该类为配置类
@EnableSwagger2 //启用Swagger2
public class Swagger2Config {
//配置多个分组
@Bean
public Docket newDocket1() {
return new Docket(DocumentationType.SWAGGER_2).groupName("A");
}
/**
* 配置swager的Bean实例
* @return
*/
@Bean
public Docket newDocket() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.enable(true)//是否启用swagger,true表示启用
.groupName("设置组名")//组名
.select()
//RequestHandlerSelectors.basePackage 指定扫描的包
//RequestHandlerSelectors.withMethodAnnotation 扫描方法上的注解
//RequestHandlerSelectors.withClassAnnotation 扫描类上的注解
//any 扫描全部
//none 不扫描
.apis(RequestHandlerSelectors.basePackage("指定要扫描的包"))
//过滤
// .paths(PathSelectors.any())
.build();
}
/**
* 创建该API的基本信息(这些基本信息会展现在文档页面中)
* 访问地址:http://项目实际地址/swagger-ui.html
* @return
*/
private ApiInfo apiInfo() {
//作者信息
Contact contact = new Contact("作者名称","个人主页", "邮箱");
return new ApiInfoBuilder()
.title("自定义标题")//标题
.description("描述该文档")
.termsOfServiceUrl("指定具体的url")//服务条件
.contact(contact)//作者对象
.version("2.0")//版本号
.license("Apache 2.0")
.licenseUrl("http://www.apache.org/licenses/LICENSE-2.0")
.extensions(new ArrayList<>())
.build();
}
}
注:如何增加了拦截器,需在WebMvcConfigurer的实现类中增加以下代码
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(localInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/user/login")
.excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**");
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/swagger-ui.html");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
启动项目,访问:http://项目实际地址/swagger-ui.html
页面如下:
常用注解: