因为我的项目是多module,为了能让多module项目中方便引用swagger,所以单独创建了一个swagger-api项目,到时需要引用swagger的项目只需要添加swagger-api的依赖就可以了。
swagger-api这里创建的是maven项目,在其pom中添加如下依赖
io.springfox
springfox-swagger2
2.9.2
io.springfox
springfox-swagger-ui
2.9.2
创建配置类SwaggerConfig
@Configuration
@EnableSwagger2
public class SwaggerConfig{
@Bean
public Docket webApiConfig(){
return new Docket(DocumentationType.SWAGGER_2)
.groupName("webapi")
.apiInfo(webApiInfo())
.select()
.paths(Predicates.not(PathSelectors.regex("/admin/.*"))) // 设置不显示项
.paths(Predicates.not(PathSelectors.regex("/error.*")))
.build();
}
private ApiInfo webApiInfo(){
return new ApiInfoBuilder()
.title("xxx-API文档")
.description("本文档描述了xxx中接口定义")
.version("1.0")
.contact(new Contact("xxx","","xxx@xxx.com"))
.build();
}
}
如果你的项目不是多module结构的,只需要在本项目中引入依赖,添加配置类即可
在其他项目中引用swagger这里我在两个项目中引用了swagger 只需要在引用项目中的pom.xml添加swagger-api的依赖即可 然后在启动类中添加配置类扫描路径 这里的包路径就是SwaggerConfig配置类的包路径,即图中所示路径,我这里多个module中的路径都一样,所以配置一个就行了
@ComponentScan(basePackages = { "com.xxx.xxx"})
启动项目后访问 localhost:项目端口/swagger-ui.html
这里我其中一个module比较单一,没有过多的配置,所以成功启动了。 另外一个项目配置了权限校验,跨域访问,拦截器等访问报错404,所以针对报错开始解决
原因 通过查找资料,了解到404是swagger的静态资源未找到,可能被拦截器拦截了,需要配置过滤 解决
@Configuration
@EnableConfigurationProperties(CorsEndpointProperties.class)
public class BasicWebConfig implements WebMvcConfigurer {
@Autowired
UserLogonInterceptor userLogonInterceptor;
@Autowired
private FunctionPermissionInterceptor permissionInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(userLogonInterceptor).addPathPatterns("/**")
.excludePathPatterns("/user/login") // 设置不拦截访问
.excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**");
// 权限校验
// registry.addInterceptor(permissionInterceptor).addPathPatterns("/**");
}
@Override
public 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/");
}
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
网上很多报404在这里配置完就解决了,但是我的在这里配置了仍然无法访问,于是继续排查 检查是否有其他拦截器,都做好相应过滤 我这里排查了所有的代码没有发现拦截器未过滤的问题,但还是无法访问,
最终经过几天的陆续排查,发现问题是访问地址的问题,我访问的是localhost:8001/swagger-ui.html,但我的项目是配置了服务名的,所以哪怕本地运行也需要添加上服务名,所以正确的访问地址是localhost:服务端口/服务名/swagger-ui.html. 注意这里根据自己配置而定,如果没有配置服务名就不用添加