近来为了项目的接口文档,而集成了swagger2,但是集成完毕后,访问swagger-ui.html却报404,检查后发现,原来是被拦截了。下面写一下我的解决方法。
首先新建 WebConfig类实现WebMvcConfigurer接口,WebMvcConfigurer接口实际上就是springBoot做拦击的一个抽象的接口,在springBoot早期的版本,使用的是WebMvcConfigurerAdapter抽象父类进行管理权限。
在WebConfig类重写addResourceHandlers方法,将不拦截的路径放入。
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void configurePathMatch(PathMatchConfigurer pathMatchConfigurer) {
}
@Override
public void configureContentNegotiation(ContentNegotiationConfigurer contentNegotiationConfigurer) {
}
@Override
public void configureAsyncSupport(AsyncSupportConfigurer asyncSupportConfigurer) {
}
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer defaultServletHandlerConfigurer) {
}
@Override
public void addFormatters(FormatterRegistry formatterRegistry) {
}
@Override
public void addInterceptors(InterceptorRegistry interceptorRegistry) {
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/statics/**").addResourceLocations("classpath:/statics/");
// 解决 SWAGGER 404报错
registry.addResourceHandler("/swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
@Override
public void addCorsMappings(CorsRegistry corsRegistry) {
}
@Override
public void addViewControllers(ViewControllerRegistry viewControllerRegistry) {
}
@Override
public void configureViewResolvers(ViewResolverRegistry viewResolverRegistry) {
}
@Override
public void addArgumentResolvers(List list) {
}
@Override
public void addReturnValueHandlers(List list) {
}
@Override
public void configureMessageConverters(List> list) {
}
@Override
public void extendMessageConverters(List> converters) {
}
@Override
public void configureHandlerExceptionResolvers(List list) {
}
@Override
public void extendHandlerExceptionResolvers(List list) {
}
@Override
public Validator getValidator() {
return null;
}
@Override
public MessageCodesResolver getMessageCodesResolver() {
return null;
}
}
这样就解决了无法访问swagger-ui的问题了。