手记

Springboot集成swagger2.6

1. 关于swagger

我们撰写的接口文档,有面向内部开发者的,也有面向外部的。很多情况下文档和代码是分离的,有好处也有坏处。而当我们写java项目想偷懒,想要自动生成接口文档时,swagger工具是个不错的选择。
在Golang中, godoc时标准化的工具,而java似乎没这么舒服。所以这里借助了swagger第三方工具,swagger是主要用于自动生成restful风格API文档以及方便开发调试的开源组件,可以与springboot友好集成。

2. pom.xml添加依赖

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.6.1</version>
</dependency>

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.6.1</version>
</dependency>

3. 添加swagger配置

  • 新增SwaggerConfig.java,用于指定基本配置及维护信息:
package com.example.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
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;

/**
 * @author moguang
 * @version 2018/9/20
 * @description: SwaggerConfig
 */
@Configuration
@ConditionalOnProperty(prefix = "swagger", value = { "enable" }, havingValue = "true")
@EnableSwagger2
public class SwaggerConfig {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                // 指定当前服务的host
                .host("example.com:443").forCodeGeneration(true)
                // 指定package下生成API文档
                .select().apis(RequestHandlerSelectors.basePackage("com.example.controller"))
                // 过滤生成链接(any()表示所有url路径)
                .paths(PathSelectors.any()).build().apiInfo(apiInfo());
    }

    // api接口作者相关信息
    private ApiInfo apiInfo() {
        Contact contact = new Contact("moguang", "", "xxx@qq.com");
        ApiInfo apiInfo = new ApiInfoBuilder().license("Apache License Version 2.0").title("Example服务接口")
                .description("接口文档").contact(contact).version("1.0").build();
        return apiInfo;
    }
}
  • 新增WebMvcConfig.java, 用于静态资源路径的注册:
package com.example.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
    /**
     * 配置静态资源路径
     *
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
        /* swagger-ui */
        registry.addResourceHandler("/swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
}

4. Controller增加swagger注解(示例)

package com.example.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RequestParam;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiParam;
import io.swagger.annotations.ApiOperation;

@Api(value = "密码相关Controller", description = "密码相关", tags = { "Credential" })
@Controller
public class PasswordController {

    @ApiOperation("确认重置密码")
    @RequestMapping(value  =  "/user/passwd/reset", method  =  RequestMethod.POST, produces  =  "application/json;charset=UTF-8")
    @ResponseBody
    public  String  updatePassword(
            @ApiParam("邮箱地址")  @RequestParam(name  =  "email")  String  email,
            @ApiParam("密码")  @RequestParam(name  =  "pwd")  String  passwd,
            @ApiParam("时间戳")  @RequestParam(name  =  "t")  String  timestamp,
            @ApiParam("签名")  @RequestParam(name  =  "sign")  String  sign) {
        // TODO: do something
        return "{"code":0}";
    }
}

更具体的注解用法可参考其他资料,如:https://www.cnblogs.com/hyl8218/p/8520994.html

5. 运行效果

springboot服务起来后,访问http(s)://yourhost:port/swagger-ui.html可显示如下效果:

6. 生产环境关闭swagger

安全起见,生产环境应当关闭swagger文档。其中一种方法如下:

  • SwaggerConfig中增加注解,对配置变量的判断
    如上面的SwaggerConfig.java加入的:
@ConditionalOnProperty(prefix = "swagger", value = { "enable" }, havingValue = "true")
  • 在application.properties或application-${profile}.properties (或yml文件)增加如下变量:
swagger.enable=false  # 关闭
# swagger.enable=true # 开启

关闭后swagger-ui.html仍然可以访问,但此时页面已经没有任何数据。当然,同时把这个url路径直接屏蔽更好。

6人推荐
随时随地看视频
慕课网APP