springboot使用swagger2及拦截器使用时导致swagger2页面无法访问的解决办法

swagger2是一个接口文档生成工具,通过一些简单的配置不仅可以使用swagger2提供的前端页面进行接口调试,还可以导出接口文档,以及方便的导入到YApi等接口文档管理平台等,废话不多说,直接看代码:

首先是依赖:


	io.springfox
	springfox-swagger2
	2.9.2


	io.springfox
	springfox-swagger-ui
	2.9.2

然后是配置文件:

@Configuration
public class Swagger2Conf {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.swagger2test"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("springboot利用swagger2构建api文档")
                .description("简单优雅的restful风格")
                .termsOfServiceUrl("http://www.baidu.com")
                .version("1.0")
                .build();
    }
}

springboot使用swagger2及拦截器使用时导致swagger2页面无法访问的解决办法_第1张图片

配置文件中的五个方法参数后四个分别对应页面中圈出的这五个部分中的四个,第一个参数是swagger2需要扫描接口的路径。

控制器相关代码:

@RestController
@RequestMapping("/user")
@Api("测试api")
public class TestCtrl {

    @Autowired
    private RestTemplate restTemplate;
    private static final Logger LOGGER = LoggerFactory.getLogger(TestCtrl.class);

    @ApiOperation(value="获取用户详细信息", notes="根据url的id来获取用户详细信息")
    @GetMapping("/test")
    public String test(String message) throws IOException {
        return "OK" + new Date();
    }
}

其中@Api及@ApiOperation是接口相关的描述信息,swagger2还有许多其他注解,此处不做赘述。

最后在启动类上加上@EnableSwagger2注解启动项目即可。

 

当使用拦截器时有可能会导致swagger2的页面无法显示,找了网上的一些方法没奏效,后来经过查证是由于拦截器的配置类继承了WebMvcConfigurationSupport类的缘故导致静态资源加载出现了问题,有两个解决方案:

1.使用老版本的WebMvcConfigurerAdapter代替WebMvcConfigurationSupport。

2.在继承了WebMvcConfigurationSupport的配置类中增加如下代码。

@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("swagger-ui.html")
            .addResourceLocations("classpath:/META-INF/resources/");
    registry.addResourceHandler("/webjars/**")
            .addResourceLocations("classpath:/META-INF/resources/webjars/");
}

 

你可能感兴趣的:(学习笔记)