SpringBoot整合Swagger框架 ,并设置接口请求头token默认值

 

 

引入maven依赖

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

        <!--防止进入swagger页面报类型转换错误,排除2.9.2中的引用,手动增加1.5.21版本-->
        <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>
        <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>

 

 

 

 

创建配置类

SwaggerConfig.java


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
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.ArrayList; /** * @author yvioo。 */ @Configuration @EnableSwagger2 //开启Swagger2 public class SwaggerConfig { /** * 配置Swagger的Docket的bean实例 * @return */ @Bean public Docket docket(Environment environment) { //设置只在开发中环境中启动swagger Profiles profiles=Profiles.of("dev"); //表示如果现在是dev环境,则返回true 开启swagger boolean flag=environment.acceptsProfiles(profiles); /*添加接口请求头参数配置 没有的话 可以忽略*/ ParameterBuilder tokenPar = new ParameterBuilder(); List<Parameter> pars = new ArrayList<>(); tokenPar.name("token").description("令牌").defaultValue("设置token默认值").modelRef(new ModelRef("string")).parameterType("header").required(false).build(); pars.add(tokenPar.build()); return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) //是否启动swagger 默认启动 .enable(flag) //所在分组 .groupName("yvioo") .select() //指定扫描的包路径 .apis(RequestHandlerSelectors.basePackage("com.example.demo.controller")) //指定扫描的请求,这里表示扫描 /hello/ 的请求 //.paths(PathSelectors.ant("/hello/**")) .build() .globalOperationParameters(pars); } /** * 配置ApiInfo信息 * @return */ private ApiInfo apiInfo() { //作者信息 Contact author = new Contact("yvioo", "https://www.cnblogs.com/pxblog/", "111@qq.com"); return new ApiInfo( "Swagger测试", "Swagger描述", "1.0", "urn:tos", author, "Apache 2.0", "http://www.apache.org/licenses/LICENSE-2.0", new ArrayList() ); } }

 

 

但是如果有其他配置继承了 WebMvcConfigurationSupport 就需要增加资源映射 不然会失效

(尽量不要使用继承的方式,可以改为实现  implements WebMvcConfigurer)

@Configuration
public class WebMvcConfigurer extends WebMvcConfigurationSupport {

    /**
     * 发现如果继承了WebMvcConfigurationSupport, 需要重新指定静态资源
     *
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations(
                "classpath:/static/");
        registry.addResourceHandler("swagger-ui.html").addResourceLocations(
                "classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations(
                "classpath:/META-INF/resources/webjars/");
        super.addResourceHandlers(registry);
    }
}

 

如果配置了拦截器 也需要去掉相应拦截

 List<String> urls = new LinkedList<>();
        urls.add("/favicon.ico");
        urls.add("/error");
        urls.add("/swagger-resources/**");
        urls.add("/webjars/**");
        urls.add("/v2/**");
        urls.add("/doc.html");
        urls.add("**/swagger-ui.html");
        urls.add("/swagger-ui.html/**");


        registry.addInterceptor(authenticationInterceptor())
                .excludePathPatterns(urls)

 

 

 

 


 

出现报错:

org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException
    at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:181) ~[spring-context-5.3.15.jar:5.3.15]
    at org.springframework.context.support.DefaultLifecycleProcessor.access$200(DefaultLifecycleProcessor.java:54) ~[spring-context-5.3.15.jar:5.3.15]
    at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.start(DefaultLifecycleProcessor.java:356) ~[spring-context-5.3.15.jar:5.3.15]
    at java.lang.Iterable.forEach(Iterable.java:75) ~[na:1.8.0_162]
    at org.springframework.context.support.DefaultLifecycleProcessor.startBeans(DefaultLifecycleProcessor.java:155) ~[spring-context-5.3.15.jar:5.3.15]
    at org.springframework.context.support.DefaultLifecycleProcessor.onRefresh(DefaultLifecycleProcessor.java:123) ~[spring-context-5.3.15.jar:5.3.15]
    at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:935) ~[spring-context-5.3.15.jar:5.3.15]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:586) ~[spring-context-5.3.15.jar:5.3.15]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:145) ~[spring-boot-2.6.3.jar:2.6.3]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:732) [spring-boot-2.6.3.jar:2.6.3]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:414) [spring-boot-2.6.3.jar:2.6.3]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:302) [spring-boot-2.6.3.jar:2.6.3]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1303) [spring-boot-2.6.3.jar:2.6.3]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1292) [spring-boot-2.6.3.jar:2.6.3]
    at com.voyah.baseline.BaseLineApplication.main(BaseLineApplication.java:13) [classes/:na]
Caused by: java.lang.NullPointerException: null
    at springfox.documentation.spi.service.contexts.Orderings$8.compare(Orderings.java:112) ~[springfox-spi-2.9.2.jar:null]
    at springfox.documentation.spi.service.contexts.Orderings$8.compare(Orderings.java:109) ~[springfox-spi-2.9.2.jar:null]
    at com.google.common.collect.ComparatorOrdering.compare(ComparatorOrdering.java:37) ~[guava-20.0.jar:na]
    at java.util.TimSort.countRunAndMakeAscending(TimSort.java:355) ~[na:1.8.0_162]
    at java.util.TimSort.sort(TimSort.java:220) ~[na:1.8.0_162]
    at java.util.Arrays.sort(Arrays.java:1438) ~[na:1.8.0_162]
    at com.google.common.collect.Ordering.sortedCopy(Ordering.java:855) ~[guava-20.0.jar:na]
    at springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider.requestHandlers(WebMvcRequestHandlerProvider.java:57) ~[springfox-spring-web-2.9.2.jar:null]
    at springfox.documentation.spring.web.plugins.DocumentationPluginsBootstrapper$2.apply(DocumentationPluginsBootstrapper.java:138) ~[springfox-spring-web-2.9.2.jar:null]
    at springfox.documentation.spring.web.plugins.DocumentationPluginsBootstrapper$2.apply(DocumentationPluginsBootstrapper.java:135) ~[springfox-spring-web-2.9.2.jar:null]
    at com.google.common.collect.Iterators$7.transform(Iterators.java:750) ~[guava-20.0.jar:na]
    at com.google.common.collect.TransformedIterator.next(TransformedIterator.java:47) ~[guava-20.0.jar:na]
    at com.google.common.collect.TransformedIterator.next(TransformedIterator.java:47) ~[guava-20.0.jar:na]
    at com.google.common.collect.MultitransformedIterator.hasNext(MultitransformedIterator.java:52) ~[guava-20.0.jar:na]
    at com.google.common.collect.MultitransformedIterator.hasNext(MultitransformedIterator.java:50) ~[guava-20.0.jar:na]
    at com.google.common.collect.ImmutableList.copyOf(ImmutableList.java:249) ~[guava-20.0.jar:na]
    at com.google.common.collect.ImmutableList.copyOf(ImmutableList.java:209) ~[guava-20.0.jar:na]
    at com.google.common.collect.FluentIterable.toList(FluentIterable.java:614) ~[guava-20.0.jar:na]
    at springfox.documentation.spring.web.plugins.DocumentationPluginsBootstrapper.defaultContextBuilder(DocumentationPluginsBootstrapper.java:111) ~[springfox-spring-web-2.9.2.jar:null]
    at springfox.documentation.spring.web.plugins.DocumentationPluginsBootstrapper.buildContext(DocumentationPluginsBootstrapper.java:96) ~[springfox-spring-web-2.9.2.jar:null]
    at springfox.documentation.spring.web.plugins.DocumentationPluginsBootstrapper.start(DocumentationPluginsBootstrapper.java:167) ~[springfox-spring-web-2.9.2.jar:null]
    at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:178) ~[spring-context-5.3.15.jar:5.3.15]
    ... 14 common frames omitted

 

 这是因为springboot版本是2.6以上版本,降低springboot版本为 2.1.10.RELEASE   

或者加上配置

spring:
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher

 

  

 

 

测试用户实体类

User.java

package com.example.demo.entity;


import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

@ApiModel("用户实体类 User")  //增加实体类接口注释
@Data   //使用Lombok插件自动生成get set方法,这样才能在swagger中显示属性值
public class User {

    @ApiModelProperty("用户ID")  //增加字段接口注释
    private Integer id;


    @ApiModelProperty("用户名")
    private String username;

}

 

 

 

测试控制器

SwaggerController.java

package com.example.demo.controller;


import com.example.demo.entity.User;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@Api(description = "该控制器描述") @RestController
public class SwaggerController { @GetMapping("/hello") public String hello(){ return "hello"; } /** * 接口返回值含有实体类,就会被swagger扫描 * * @return */ @ApiOperation("查询用户方法注释") @GetMapping(value = "/get/{id}") public User get(@ApiParam("请求参数注释") @PathVariable(value = "id")Integer id){ return new User(); } }

 

@ApiImplicitParam:
作用在方法上,表示单独的请求参数 
参数: 
1. name :参数名。 
2. value : 参数的具体意义,作用。 
3. required : 参数是否必填。 
4. dataType :参数的数据类型。 

 

 

 

使用dev环境 启动项目后  浏览器打开 http://localhost:8081/swagger-ui.html#/   我这里用的端口是8081

显示效果

 

 

 整合 knife4j框架参考:https://www.cnblogs.com/pxblog/p/14831211.html

 

2.1.10.RELEASE
posted @ 2020-05-23 15:51  yvioo  阅读(3943)  评论(0编辑  收藏  举报