maven依赖

<!-- swagger -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>${swagger.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>io.swagger</groupId>
                    <artifactId>swagger-annotations</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>io.swagger</groupId>
                    <artifactId>swagger-models</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-annotations</artifactId>
            <version>1.5.21</version>
        </dependency>
        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-models</artifactId>
            <version>1.5.21</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>${swagger.version}</version>
        </dependency>

Config配置

package com.zrt.swagger;
 
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.OAuthBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger.web.SecurityConfiguration;
import springfox.documentation.swagger.web.UiConfiguration;
import springfox.documentation.swagger.web.UiConfigurationBuilder;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
 
import static com.google.common.collect.Lists.newArrayList;
 
/**
 * API文档生成类
 */
@Configuration
@EnableSwagger2
public class Swagger2Config {
 
    @Value("${swagger.base-package:com.zrt.controller}")
    protected String basePackage;
 
    @Value("${gateway-service:127.0.0.1:8765}")
    private String serviceip;
 
    @Value("${swagger.client.state:web}")
    private String state;
 
    @Value("${swagger.api.title:后台系统接口  APIs}")
    protected String apiTitle;
 
    @Value("${swagger.api.description:相关接口详细说明}")
    protected String apiDescription;
 
    @Value("${swagger.api.com:中软通}")
    protected String apiCom;
 
    @Value("${swagger.api.com-url:http://www.zrt.com/}")
    protected String apiComUrl;
 
    @Value("${swagger.api.version:0.0.1}")
    protected String apiVersion;
 
    @Value("${swagger.api.clientId:web}")
    protected String clientId;
 
    @Value("${swagger.api.scope:openid}")
    protected String scope;
 
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage(basePackage))
                .paths(PathSelectors.any())
                .build()
                .securitySchemes(newArrayList(oauth()));
    }
 
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title(apiTitle)
                .description(apiDescription)
                .contact(new Contact(apiCom, apiComUrl, null))
                .version(apiVersion)
                .build();
    }
 
    protected SecurityScheme oauth() {
        return new OAuthBuilder()
                .name(state)
                .grantTypes(newArrayList(new ImplicitGrant(new LoginEndpoint("http://" + serviceip + "/relog"),
                        "access_code")))
                .build();
    }
 
    @Bean
    public SecurityConfiguration defBuilder() {
        return new SecurityConfiguration(clientId, null, null, state, scope,
                null, true);
    }
 
    @Bean
    UiConfiguration uiConfig() {
        return UiConfigurationBuilder.builder()
                .validatorUrl("http://" + serviceip + "/validator")
                .build();
    }
 
}

.groupName("商品接口文档")   设置栏目名 .select()  初始化并返回一个API选择构造器 .paths(PathSelectors.any())   设置路径筛选 .apis(RequestHandlerSelectors.basePackage("com.mao.swagger.goods.>controller"))  添加路径选择条件 .build();    构建

PathSelectors类的方法:

Predicate any():满足条件的路径,该断言总为true Predicate none():不满足条件的路径,该断言总为false Predicate regex(final String pathRegex):符合正则的路径

RequestHandlerSelectors类的方法:

Predicate<RequestHandler> any():返回包含所有满足条件的请求处理器的断言,该断言总为true

Predicate<RequestHandler> none():返回不满足条件的请求处理器的断言,该断言总为false

Predicate<RequestHandler> basePackage(final String basePackage):返回一个断言(Predicate),该断言包含所有匹配basePackage下所有类的请求路径的请求处理器

接口参数(注解)

@Api                     //用在类上,说明该类的作用
@ApiOperation            //用在方法上,增加方法说明
@ApiImplicitParams       //用在方法上,包含一组参数说明
@ApiImplicitParam        //用在ApiImplicitParams中,给方法入参增加说明
@ApiResponses            //用于表示一组响应
@ApiResponse             //用在@ApiResponses中,一般用来表达一个错误的相应信息
  |code: 错误码
  |message:  信息
  |response:  抛出异常类
@ApiModel                //用在实体类上,描述一个model的信息
@ApiModelProperty        //用在实体类的参数上,描述一个参数的信息

例子

package com.zrt.controller;
 
 
import com.zrt.entity.ResponseResult;
import com.zrt.exception.CommonExceptionHander;
import com.zrt.service.ResultService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
 
import java.util.Date;
 
@RestController
@Api("告警消息API")
@RequestMapping("/result")
public class ResultController {
 
    private static Logger logger = LoggerFactory.getLogger(ResultController.class);
 
    @Autowired
    private ResultService resultService;
 
    @ApiOperation("命中告警")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "rule_id", value = "规则id", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "hit_time", value = "命中时间", required = true, paramType = "query"),
            @ApiImplicitParam(name = "hit_source", value = "触网源", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "hit_source_type", value = "触网源类型,默认为场所类型", dataType = "string",  paramType = "query"),
            @ApiImplicitParam(name = "keyword", value = "关键字", dataType = "string", required = true,  paramType = "query"),
            @ApiImplicitParam(name = "keyword_type", value = "关键字类型", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "encode", value = "归属地", dataType = "string",  paramType = "query")
    })
    @RequestMapping(value = "/hit-alarm",method = RequestMethod.POST)
    public ResponseResult hitAlarm(@RequestParam(name = "rule_id") String rule_id,
                                   @RequestParam(name = "hit_time") Date hit_time,
                                   @RequestParam(name = "hit_source") String hit_source,
                                   @RequestParam(name = "hit_source_type", required = false) String hit_source_type,
                                   @RequestParam(name = "keyword") String keyword,
                                   @RequestParam(name = "keyword_type") String keyword_type,
                                   @RequestParam(name = "encode", required = false) String encode){
        logger.info("命中规则<rule_id:" + rule_id + ",hit_time:" + hit_time + ",hit_source:" + hit_source + ",keyword:" + keyword + ">");
        try {
            resultService.hitAlarm(rule_id, hit_time, hit_source, hit_source_type, keyword, keyword_type, encode);
            return CommonExceptionHander.handleResultSucc(null);
        } catch (Exception e) {
            return CommonExceptionHander.handleResultFail("发送警告失败");
        }
    }
 
}
package com.zrt.entity.po;
 
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
 
@Data
@ApiModel("规则表")
public class MonitorRule {
    @ApiModelProperty("注册表的id(不需要传入)")
    private String rule_id;
 
    @ApiModelProperty("布控类型:0 黑名单布控 ;1 归属地布控;2 区域布控;3 案件布控")
    private Integer rule_type;
 
    @ApiModelProperty("规则名称")
    private String rule_name;
 
    @ApiModelProperty("布控区域")
    private String monitor_area;
 
    @ApiModelProperty(value = "有效期",required = false)
    private Date validate;
}

注意:@ApiImplicitParam的参数说明(@ApiModelProperty中用法一样):

paramType:指定参数放在哪个地方header:请求参数放置于RequestHeader,使用@RequestHeader获取 query:请求参数放置于请求地址,使用@RequestParam获取 path:(用于restful接口)-->请求参数的获取:@PathVariable body:(不常用) form(不常用)
--------------
name:参数名
--------------
dataType:参数类型
--------------
required:参数是否必须传true | false
--------------
value:说明参数的意思
--------------
defaultValue:参数的默认值

最后

调试的时候把项目跑起来进到 http://localhost:XXXX/swagger-ui.html# 就能进到api调试界面了