springboot 集成swagger

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路径直接屏蔽更好。
  • 转载:https://blog.csdn.net/moxiaomomo/article/details/82882397
  •  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值