欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Spring Boot 集成Swagger2

程序员文章站 2022-07-03 08:42:19
...

依赖准备

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

        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>19.0</version>
        </dependency>

Swagger 配置类

@Configuration
@EnableSwagger2
public class SwaggerApp {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //此处 写你的controller所在包路径
                .apis(RequestHandlerSelectors.basePackage("com.xxx.controller"))
                .paths(PathSelectors.any())
                .build();
    }
    //构建 api文档的详细信息函数,注意这里的注解引用的是哪个
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                //页面标题
                .title("管理系统API")
                //创建人
                .contact(new Contact("tyl", "", ""))
                //版本号
                .version("1.0")
                //描述
                .description("API 描述")
                .build();
    }
}

注意要点

1、SpringBoot启动类Application中添加注解 @EnableSwagger2
2、使swagger静态资源可访问 继承WebMvcConfigurationSupport类重写addResourceHandlers方法

@Configuration
public class ResourceHandlersConfig extends WebMvcConfigurationSupport {
    /**
     * 使 swagger2的静态资源可访问
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations(
                "classpath:/static/");
        registry.addResourceHandler("swagger-ui.html").addResourceLocations(
                "classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations(
                "classpath:/META-INF/resources/webjars/");
        super.addResourceHandlers(registry);
    }
}

3、如果你的项目中存在shiro、spring security等权限控制,需要在拦截器中配置忽略的请求路径

@Bean
    public ShiroFilterFactoryBean shirFilter(@Qualifier("securityManager")DefaultWebSecurityManager securityManager,
                                             EhCacheManager ehCacheManager,DefaultWebSessionManager sessionManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        // 必须设置SecuritManager
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        Map<String, Filter> filters = shiroFilterFactoryBean.getFilters();//获取filters
        filters.put("authc", myFormAuthenticationFilter());
        filters.put("kickout", kickoutSessionControlFilter(ehCacheManager,sessionManager));

        // 拦截器
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>()

        //不拦截 接口文档
        filterChainDefinitionMap.put("/swagger-resources/**","anon");
        filterChainDefinitionMap.put("/webjars/**", "anon");
        filterChainDefinitionMap.put("/v2/**", "anon");
        filterChainDefinitionMap.put("/swagger-ui.html","anon");

        filterChainDefinitionMap.put("/**", "authc,kickout");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return shiroFilterFactoryBean;
    }

使用

@Api("类描述说明")
@RestController
@RequestMapping("/***")
public class CostAnalysisController {

    @ApiOperation(value = 方法描述说明")
    @RequestMapping(value = "/getCityData",method = {RequestMethod.POST})
    public Result getCityData(@RequestBody CityTypeCostParam param) {
        Result result = new Result();
        result.setStatus(0);
        result.setStatus(1);
        result.setMessage("查询成功");
        return result;
    }
}

使用@RequestBody 注解的参数类 会自动识别,swagger具体的使用方法请自行百度。

访问接口文档页面

sopringBoot启动的端口
http://127.0.0.1:8081/swagger-ui.html
Spring Boot 集成Swagger2

可能会遇到的问题

问题1
访问页面报404
未继承WebMvcConfigurationSupport类重写addResourceHandlers方法,见注意要点2

问题2
Unable to infer base url. This is common when using dynamic servlet registration or when the API is behind an API Gateway. The base url is the root of where all the swagger resources are served. For e.g. if the api is available at http://example.org/api/v2/api-docs then the base url is http://example.org/api/. Please enter the location manually:
(1)检查启动类中Application中是否添加注解@EnableSwagger2
(2)权限过滤器中 是否配置了忽略的请求路径
Spring Boot 集成Swagger2
问题3
同一个接口在接口文档页面出现多次,这是由于再写接口时没有指定接口的请求方式
Spring Boot 集成Swagger2

只需要在controller请求方法中指定method,如下

@RequestMapping(value = "/xxxx",method = RequestMethod.POST)