2

新手上路-搭建项目-springboot-swagger2

swagger2 是一个接口文档软件
  • 界面如下

swagger2测试

gradle添加

compile("io.springfox:springfox-swagger2:$swagger2Version")
compile("io.springfox:springfox-swagger-ui:$swaggerUi")
  • 这里使用2.4.0版本可以正常使用

swagger2配置文件

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@EnableSwagger2
@Configuration
public class Swagger2Config {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.seal_de.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("swagger2测试")
                .description("新手上路-swagger2。https://git.oschina.net/sealde/springboot-javaconfig/tree/dev2")
                .termsOfServiceUrl("https://git.oschina.net/sealde/springboot-javaconfig/tree/dev2")
                .version("0.0.1")
                .contact(new Contact("seal_de", "https://git.oschina.net/sealde", "seal.de@foxmail.com"))
                .build();
    }
}

配置资源处理器

@Configuration
public class WebConfig 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/");
    }
    
    ...
}

注意事项

  • 如果有配置token验证等机制,建议将swagger2的一些请求放行

  • 下面只是一个例子,看实际情况进行配置

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
    ...

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
       registry.addInterceptor(new TokenInterceptor(tokenManager))
               .addPathPatterns("/**").excludePathPatterns("/configuration/ui", "/configuration/security", "/v2/api-docs", "/swagger**");
    }
    
    ...
 }

最后


seal_de
46 声望3 粉丝