搭建思路

1、swagger相关配置单独放在一个文件,放入到.gitignore,这样不上传
2、swagger的代码不入侵业务代码中

开始

1、引入pom

<dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-swagger2</artifactId>
	<version>2.7.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-swagger-ui</artifactId>
	<version>2.7.0</version>
</dependency>

2、建立Swagger配置文件

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.*;


@Configuration
@EnableSwagger2
public class SwaggerConfig implements WebMvcConfigurer {

    @Value("${swagger.enable:false}")
    private boolean enable;

    /**
     * 请求头
     *
     * @return 请求头集合
     */
    private Map<String, String> getHeadMap() {
//        String clientId = "phjr";
        String clientId = "testClientId123";
        String timeStamp = TimeUtil.formatDate(new Date(),TimeUtil.TRANS_TIME_PATTERN3);
        String secret = SecretKeyCons.secretMap.get(clientId);
        String sign = Md5Util.getMd5(secret+timeStamp);

        Map<String, String> head = new HashMap<>();
        head.put("clientId", clientId);
        head.put("JSESSIONID", "6B719951CAF64464479EE3A4AF5C1875");
        head.put("timeStamp", timeStamp);
        head.put("sign", sign);
        return head;
    }


    @Bean
    public Docket productApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .pathMapping("/")
                .select()
                .apis(RequestHandlerSelectors.basePackage("org.jxzx.phjr.api.controller"))
                .paths(PathSelectors.any())
                .build().globalOperationParameters(getParameter());
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("基础服务的适配类")
                .description("提供可视化接口文档与接口测试工具")
                .termsOfServiceUrl("http://www.xw.com/")
                .license("xw版权所有")
                .build();
    }

    private List<Parameter> getParameter(){

        Map<String, String> headMap = getHeadMap();

        List<Parameter> pars = new ArrayList<>();
        pars.add(getParameterBuilder("JSESSIONID","JES","string",headMap.get("JSESSIONID")));
        pars.add(getParameterBuilder("clientId","用户名","string",headMap.get("clientId")));
        pars.add(getParameterBuilder("timeStamp","yyyyMMddHHmmss","string",headMap.get("timeStamp")));
        pars.add(getParameterBuilder("sign","sign","string",headMap.get("sign")));

        return pars;
    }

    private Parameter getParameterBuilder(String name,String des,String type,String value){
        ParameterBuilder tokenPar = new ParameterBuilder();
        tokenPar.name(name)
                .description(des)
                .modelRef(new ModelRef(type))
                .parameterType("header")
                .defaultValue(value)
                .required(true);
        return tokenPar .build();
    }

}

部分代码解释
1、公司项目需要加入请求头,故有getParameter()方法
2、@Value("$
")本来是想通过开关控制,结果代码上传后,配置文件也是随着变化,效果不大
3、.paths(PathSelectors.any())这一行是指扫描全部的controller的类,由于不入侵业务代码,所以启动后找controller类名就行

3、被拦截时,代码处理

有些项目很通过拦截会把所有请求拦截掉,swagger配置好了也不能访问,故排除拦截的代码展示

@Configuration
public class WebAppConfigAdapter implements WebMvcConfigurer {
 
    @Resource
    private LoginAuthInterceptor loginAuthInterceptor;


    @Bean
    public HttpMessageConverter<String> responseBodyConverter() {
        StringHttpMessageConverter converter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
        List<MediaType> supportedMediaTypes = new ArrayList<MediaType>();
        supportedMediaTypes.add(MediaType.APPLICATION_XML);
        supportedMediaTypes.add(MediaType.TEXT_PLAIN);
        converter.setSupportedMediaTypes(supportedMediaTypes);
        return converter;
    }

    /*********************************覆盖默认****************************************/

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //登录拦截
        addLoginAuthInterceptor(registry);
    }


    private void addLoginAuthInterceptor(InterceptorRegistry registry) {
        registry.addInterceptor(loginAuthInterceptor)
                .addPathPatterns(Lists.newArrayList(""))
                .excludePathPatterns(Lists.newArrayList("/swagger-ui.html"
                        ,"/webjars/springfox-swagger-ui/**"
                        , "/swagger-resources/**"));
    }