springboot整合swagger2

                                      springboot整合swagger2

一、简介

        在工作中,不管是前后端分离,还是微服务,还是其他方式的接口的调用,都需要编写和维护接口文档。Swagger可以帮助我们更好的编写和维护API文档,提供Restful风格的API,提供的maven依赖可以更好的集成在spring项目中。

二、整合

a.添加maven依赖

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

b.添加swagger配置

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;

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //swagger要扫描的包路径
                .apis(RequestHandlerSelectors.basePackage("com.voodone.core.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("中心控制服务的接口信息")
                .description("总中心控制服务的接口信息")
                .termsOfServiceUrl("localhost:9007/ruleengine")
                .contact(new Contact("Swagger测试", "localhost:9007/ruleengine/swagger-ui.html", "baidu@qq.com"))
                .version("V1.0.0")
                .build();
    }
}

访问:http://localhost:9007/core-web/swagger-ui.html

c.swagger扫描的包中添加文档说明

类进行添加说明

@Api(tags = "服务配置接口", description = "服务配置(设备ID的生成规则)")

方法进行添加说明

    @PostMapping(value = "/boxIdRule")
    @ApiOperation(value = "设备ID的生成规则", notes = "不需要提供参数", httpMethod = "POST")
    public String query(HttpServletRequest request, HttpServletResponse response) {
        try {
            ConfigInfo configInfo = configInfoService.getConifgInfo("BOXID_CREATE_RULE");
            BoxIdRuleVo boxIdRuleVo = BoxIdRuleVo.modelToVo(configInfo);
            return ResponseResult.successResponse(boxIdRuleVo);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.enumResponse(ResponseError.OPERATION_FAILURE);
        }
    }

    @PostMapping(value = "/query")
    @ApiOperation(value = "设备ID的查询", notes = "提供BOXID参数", httpMethod = "POST")
    @ApiImplicitParam(name = "boxId", value = "设备ID", required = true)
    public String query(@RequestParam(required = true) String boxId) {
        try {
            BoxInfo boxInfo = boxInfoService.queryBoxId(boxId);
            BoxInfoVo boxInfoVo = BoxInfoVo.modelToVo(boxInfo);
            return ResponseResult.successResponse(boxInfoVo);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.enumResponse(ResponseError.OPERATION_FAILURE);
        }
    }

    @PostMapping(value = "/bind")
    @ApiOperation(value = "设备ID的绑定", notes = "需要提供三个参数", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "boxId", value = "设备ID", required = true),
            @ApiImplicitParam(name = "barcode", value = "条形码", required = true),
            @ApiImplicitParam(name = "boxModel", value = "型号", required = true)
    })
    public String save(@RequestParam(required = true) String boxId,
                       @RequestParam(required = true) String barcode,
                       @RequestParam(required = true) String boxModel) {
        try {
            BoxInfo boxInfo = new BoxInfo();
            boxInfo.setBarcode(barcode);
            boxInfo.setBoxId(boxId);
            boxInfo.setBoxModel(boxModel);
            boxInfo.setBindTime(new Date());
            boxInfo.setCreateTime(new Date());
            boxInfoService.bindBarcode(boxInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.enumResponse(ResponseError.OPERATION_FAILURE);
        }
        return ResponseResult.okResponse();
    }

相关注解的说明:

  1. @Api:注解可以用来标记当前Controller的功能。
  2. @ApiOperation:注解用来标记一个方法的作用。
  3. @ApiImplicitParam:注解用来描述一个参数,可以配置参数的中文含义,也可以给参数设置默认值,这样在接口测试的时候可以避免手动输入。
  4. 如果有多个参数,则需要使用多个@ApiImplicitParam注解来描述,多个@ApiImplicitParam注解需要放在@ApiImplicitParams注解中。
  5. 注意@ApiImplicitParam注解中虽然可以指定参数是必填的,但是却不能代替@RequestParam(required = true),前者的必填只是在Swagger2框架内必填,抛弃了Swagger2,这个限制就没用了,所以假如开发者需要指定一个参数必填,@RequestParam(required = true)注解还是不能省略。
  6. 如果参数是一个对象,对于参数的描述也可以放在实体类中。
@Data
@ApiModel(description = "保存绑定的信息")
public class BindModel implements Serializable {

    @ApiModelProperty(name = "设备ID",required = true,notes = "设备ID")
    private String boxId;

    @ApiModelProperty(name = "条形码",required = true,notes = "条形码")
    private String barcode;

    @ApiModelProperty(name = "型号",required = true,notes = "型号")
    private String boxModel;
}
    @PostMapping(value = "/bindTmp")
    @ApiOperation(value = "设备ID的绑定", notes = "需要提供三个参数", httpMethod = "POST")
    public String saveModel(@RequestBody BindModel bindModel) {
        try {
            BoxInfo boxInfo = new BoxInfo();
            boxInfo.setBarcode(bindModel.getBarcode());
            boxInfo.setBoxId(bindModel.getBoxId());
            boxInfo.setBoxModel(bindModel.getBoxModel());
            boxInfo.setBindTime(new Date());
            boxInfo.setCreateTime(new Date());
            boxInfoService.bindBarcode(boxInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.enumResponse(ResponseError.OPERATION_FAILURE);
        }
        return ResponseResult.okResponse();
    }

三、消除拦截

import com.qcloud.wcs.web.interceptor.UserLoginInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class WebAppConfigurer extends WebMvcConfigurerAdapter {

    //关键,将拦截器作为bean写入配置中
    @Bean
    public UserLoginInterceptor myInterceptor(){
        return new UserLoginInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //多个拦截器组成一个拦截器链
        // addPathPatterns用于添加拦截规则
        // excludePathPatterns用户排除拦截
        registry.addInterceptor(myInterceptor()).addPathPatterns("/**")//对来自/** 全路径请求进行拦截
        .excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**"); //swagger请求通过
        super.addInterceptors(registry);
    }
}

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值