springboot配置swagger

导航

    • 导包
    • 编写swagger配置文件
    • 报错
    • 成功

导包

首先确保引入了包:
版本自己可以去种牙仓库上面看看:中央仓库

    <!-- swagger2-UI-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>

编写swagger配置文件

配置文件的SWAGGER_SCAN_BASE_PACKAGE 路径一定要注意
然后controller里面一定要有一个

@Api(tags = "TestController", description = "测试controller")

要不然都是空的,肯定不行的…


@Configuration
@EnableSwagger2
public class SwaggerConfig {

    public static final String SWAGGER_SCAN_BASE_PACKAGE = "com.mr.web.controller";
    public static final String VERSION = "1.0.0";

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("web")
                .description("This is to show api description")
                .license("Apache 2.0")
                .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")
                .termsOfServiceUrl("")
                .version(VERSION)
                .contact(new Contact("", "", "[email protected]"))
                .build();
    }

    @Bean
    public Docket customImplementation() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage(SWAGGER_SCAN_BASE_PACKAGE))
                .paths(PathSelectors.any())
                .build();
    }

}

然后注意一定要swagger被扫描到

报错

我端口弄成的80,所以路径如下:
http://localhost/swagger-ui.html#/
No mapping for GET /swagger-ui.html
启动之后,访问不到,想起来,swagger需要访问静态资源,但是我们没有配置,那就配置静态资源映射

@Configuration
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");

        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");

    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //登录拦截
        registry.addInterceptor(new LoginInterceptor());
    }

}

成功

再次启动:访问http://localhost/swagger-ui.html#/成功,
springboot配置swagger_第1张图片

你可能感兴趣的:(springboot,springboot整合)