一、SpringBoot依赖和实例代码准备
本实例基于SpringBoot搭建,所需要的配置和依赖很少,下面添加主要的依赖
io.springfox springfox-swagger22.9.2 com.github.xiaoymin knife4j-spring-boot-starter2.0.2
二、配置和页面展示
上面已经准备了基本的API接口,下面进行swagger的配置
@Configuration //注入容器中
@EnableSwagger2
@EnableKnife4j
@ConditionalOnProperty(value = {"knife4j.enable"}, matchIfMissing = true)
public class SwaggerConfig implements WebMvcConfigurer {
@Bean
public Docket createRestApi(){
ParameterBuilder tokenPar = new ParameterBuilder();
List pars = new ArrayList<>();
tokenPar.name("token").description("令牌").defaultValue("设置token默认值").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
pars.add(tokenPar.build());
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
//是否开启swagger默认开启 Api文档表示开发时可以查看
.enable(true)
//创建我们构造器用于定义swagger生成文档中包含哪些接口和方法 告诉扫描包路径
.select()
//扫描包路径 一般开发使用
// .apis(RequestHandlerSelectors.basePackage("com.liang.service"))
//扫描方法上的注解
// .apis(RequestHandlerSelectors.withMethodAnnotation(GetMapping.class))
//扫描类上的注解
// .apis(RequestHandlerSelectors.withClassAnnotation("com.liang.controller.EmpController"))
//扫描任何接口
// .apis(RequestHandlerSelectors.any())
.apis(RequestHandlerSelectors.basePackage("com.lingnan.club.controller"))
//paths过滤什么路径 扫描条件ant根据请求路径定义Docket容器需要包含控制器中哪些方法
.paths(PathSelectors.any())
.build()
.globalOperationParameters(pars)
.apiInfo(apiInfo())
.pathMapping("/"); //指定路径
}
private ApiInfo apiInfo(){
return new ApiInfoBuilder().title("SpringBoot-hi-app-Swagger2 API")
.description("SpringBoot-项目lnu-club")
.contact(new Contact("岭南师范学院","http://localhost:9090/","#"))
.version("1.0")
.build();
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjarsapi-docs","/webjars/**",
"/v2/**","/api/**","/doc.html")
.anonymous()
// 除上面外的所有请求全部需要鉴权认证
.anyRequest().authenticated();
//把token校验过滤器添加到过滤器链中
http.addFilterBefore(jwtAuthenticationTokenFilter,UsernamePasswordAuthenticationFilter.class);
//配置异常处理器 => 自定义的
http.exceptionHandling()
//配置认证失败处理器
.authenticationEntryPoint(authenticationEntryPoint)
.accessDeniedHandler(accessDeniedHandler);
//允许跨域
http.cors();
}
三、测试
swagger-bootstrap-ui默认访问地址是:http://host:{port}/doc.html



