Spring Boot 2 集成 Swagger2

1 简介

Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新 。接口的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步。Swagger 让部署管理和使用功能强大的API从未如此简单。

2 pom文件添加Swagger2依赖

    
        1.8
        2.9.2
    
    
    
        
            io.springfox
            springfox-swagger2
            ${swagger2.version}
        
        
            io.springfox
            springfox-swagger-ui
            ${swagger2.version}
        

3 创建Swagger2配置类

swagger配置类建议放在和application.java启动类在同一个包里面,这样会被自动扫描到。

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    /**
     * 初始化创建Swagger Api
     */
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                // 详细信息定制
                .apiInfo(apiInfo())
                .select()
                // 指定当前包路径
                .apis(RequestHandlerSelectors.basePackage("com.tickstep.demo"))
                // 只扫描有注解的api,用这种方式更灵活//.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                // 扫描所有 .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build();
    }

    /**
     * 添加摘要信息
     */
    private ApiInfo apiInfo() {
        // 用ApiInfoBuilder进行定制
        return new ApiInfoBuilder()
                .title("Spring boot 集成 Swagger2 API工具测试")
                .description("本接口文档是从代码自动构建而来,如果接口有更改请更新后台")
                .contact(new Contact("多啦E梦的博客", null, null))
                .version("0.0.1")
                .build();
    }
}

启动application,然后直接访问 http://localhost:8280/swagger-ui.html 即可查看swagger自动生成的api接口文档

4 更改Swagger访问路径

Swagger默认是访问路径是/swagger-ui.html,但有时候我们需要更改这个接口访问路径,以方便对后台URL接口的统一管理。
打开 springfox-swagger-ui.jar 包,我们可以看出swagger web 端UI的资源全部在这里面


springfox-swagger-ui.jar

这样思路就简单了,可以采取两种方法
1,我们可以把这个里面的资源全部拷贝到我们的resources目录,然后更改对应的路径映射即可(可能有些资源文件也需要改一下)
2,我们直接写个ModelAndView接口进行内部重定向

第2种方式侵入性低,我们选用这种
直接在SwaggerConfig.java文件增加以下代码


@Configuration
@EnableSwagger2
public class SwaggerConfig {

    // 指定文档访问URL路径
    // 例如指定以下路径,则通过这个URL访问:http://localhost:8280/actuator/swagger/swagger-ui.html
    private static final String DEFAULT_PATH = "/actuator/swagger";

    /**
     * SwaggerUI资源访问
     */
    @Bean
    public SimpleUrlHandlerMapping swaggerUrlHandlerMapping(ServletContext servletContext,
                                                            @Value("${swagger.mapping.order:10}") int order) throws Exception {
        SimpleUrlHandlerMapping urlHandlerMapping = new SimpleUrlHandlerMapping();
        Map urlMap = new HashMap<>();

        // webjars
        PathResourceResolver pathResourceResolver = new PathResourceResolver();
        pathResourceResolver.setAllowedLocations(new ClassPathResource("META-INF/resources/webjars/"));
//            pathResourceResolver.setUrlPathHelper(new UrlPathHelper());
        ResourceHttpRequestHandler resourceHttpRequestHandler = new ResourceHttpRequestHandler();
        resourceHttpRequestHandler.setLocations(Arrays.asList(new ClassPathResource("META-INF/resources/webjars/")));
        resourceHttpRequestHandler.setResourceResolvers(Arrays.asList(pathResourceResolver));
        resourceHttpRequestHandler.setServletContext(servletContext);
        resourceHttpRequestHandler.afterPropertiesSet();
        //设置新的路径
        urlMap.put(DEFAULT_PATH + "/webjars/**", resourceHttpRequestHandler);

        // resources
        PathResourceResolver pathResourceResolverOfRes = new PathResourceResolver();
        pathResourceResolverOfRes.setAllowedLocations(new ClassPathResource("META-INF/resources/"));
//            pathResourceResolver.setUrlPathHelper(new UrlPathHelper());
        ResourceHttpRequestHandler resourceHttpRequestHandlerOfRes = new ResourceHttpRequestHandler();
        resourceHttpRequestHandlerOfRes.setLocations(Arrays.asList(new ClassPathResource("META-INF/resources/")));
        resourceHttpRequestHandlerOfRes.setResourceResolvers(Arrays.asList(pathResourceResolverOfRes));
        resourceHttpRequestHandlerOfRes.setServletContext(servletContext);
        resourceHttpRequestHandlerOfRes.afterPropertiesSet();
        //设置新的路径
        urlMap.put(DEFAULT_PATH + "/**", resourceHttpRequestHandlerOfRes);

        urlHandlerMapping.setUrlMap(urlMap);
        //调整DispatcherServlet关于SimpleUrlHandlerMapping的排序
        urlHandlerMapping.setOrder(order);
        return urlHandlerMapping;
    }

    /**
     * SwaggerUI接口访问
     */
    @Controller
    @ApiIgnore
    @RequestMapping(DEFAULT_PATH)
    public static class SwaggerResourceController implements InitializingBean {

        @Autowired
        private ApiResourceController apiResourceController;

        @Autowired
        private Environment environment;

        @Autowired
        private DocumentationCache documentationCache;

        @Autowired
        private ServiceModelToSwagger2Mapper mapper;

        @Autowired
        private JsonSerializer jsonSerializer;

        private Swagger2Controller swagger2Controller;

        @Override
        public void afterPropertiesSet() {
            swagger2Controller = new Swagger2Controller(environment, documentationCache, mapper, jsonSerializer);
        }

        /**
         * 首页
         */
        @RequestMapping
        public ModelAndView index() {
            ModelAndView modelAndView = new ModelAndView("redirect:" + DEFAULT_PATH + "/swagger-ui.html");
            return modelAndView;
        }

        @RequestMapping("/swagger-resources/configuration/security")
        @ResponseBody
        public ResponseEntity securityConfiguration() {
            return apiResourceController.securityConfiguration();
        }

        @RequestMapping("/swagger-resources/configuration/ui")
        @ResponseBody
        public ResponseEntity uiConfiguration() {
            return apiResourceController.uiConfiguration();
        }

        @RequestMapping("/swagger-resources")
        @ResponseBody
        public ResponseEntity> swaggerResources() {
            return apiResourceController.swaggerResources();
        }

        @RequestMapping(value = "/v2/api-docs", method = RequestMethod.GET, produces = {"application/json", "application/hal+json"})
        @ResponseBody
        public ResponseEntity getDocumentation(
                @RequestParam(value = "group", required = false) String swaggerGroup,
                HttpServletRequest servletRequest) {
            return swagger2Controller.getDocumentation(swaggerGroup, servletRequest);
        }
    }
}

直接更改这个路径配置即可更改swagger的访问路径

private static final String DEFAULT_PATH = "/actuator/swagger";

重新运行application,然后接口访问
http://localhost:8280/actuator/swagger/swagger-ui.html

swagger ui

5 集成上传File文件接口

我们Controller上备注接口描述的时候,file比较特殊。需要按照以下规则进行备注。
dataType是"__file"类型:

 @PostMapping("/fileUpload")
    @ApiImplicitParams({@ApiImplicitParam(paramType = "form", dataType="__file", name = "file",
            value = "材料文件啊", required = false)})
    public String fileUpload(MeterialUploadForm form) {
        return form.getFile() == null ? "file is null" : form.getFile().getOriginalFilename();
    }

6 资源

代码示例请访问:https://gitlab.com/feny-blog/springboot-integrate-swagger.git

你可能感兴趣的:(Spring Boot 2 集成 Swagger2)