springboot 整合swagger 入门 使用

1.前提

一定要看好版本。

Springboot ✚ Swagger各版本整理_swagger版本_qq_33334411的博客-CSDN博客

我的版本:

	    <dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-boot-starter</artifactId>
			<version>3.0.0</version>
		</dependency>

2. 使用

新建一个boot web项目之后,导入上述依赖。

在confi包下新建一个SwaggerConfig.java配置类

Swgger2Config.java


@Configuration
@EnableSwagger2 // 3.0版本加不加无所谓
public class Swagger2Config {

    @Bean
    public Docket coreApiConfig(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(adminApiInfo())
                .groupName("group1")
                .select()
                .build();
    }

    private ApiInfo adminApiInfo(){
        return new ApiInfoBuilder()
                .title("后台管理系统--api文档")
                .description("后台管理系统接口描述")
                .version("1.0")
                .contact(new Contact("郡主喵","http://baidu.com","[email protected]"))
                .build();
    }
}

在controller包新建HelloController.java

@RestController
@ResponseBody
@Api(tags = "你好相关接口:")
public class HelloController {

    @GetMapping("/hellow")
    @ApiOperation("这是一个测试接口")
    public HelloVO hello(){
        return new HelloVO("qhx",11);
    }
}

在modle.vo下新建HelloVO.java

@ApiModel(value = "HelloVO",description = "你好相关接口的信息封装")
public class HelloVO {
    @ApiModelProperty("姓名")
    private String name;
    @ApiModelProperty("年龄")
    private Integer age;

    public String getName() {
        return name;
    }

    public Integer getAge() {
        return age;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public HelloVO(String name, Integer age) {
        this.name = name;
        this.age = age;
    }
}

application.yml/properties文件中添加

spring:
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher

运行,访问 http://localhost:8081/swagger-ui/index.html

 看到如上,及成功。

一般常用的swagger2注解

@Api:修饰整个类,描述Controller的作用
@ApiOperation:描述一个类的一个方法,或者说一个接口
@ApiParam:单个参数描述
@ApiModel:用对象来接收参数
@ApiModelProperty:用对象接收参数时,描述对象的一个字段
@ApiImplicitParam:一个请求参数 @ApiImplicitParams:多个请求参数

3.报错解决

1.Unable to start web server; nested exception is org.springframework.context.ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean.

忘加这个。

 2. Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException

SpringBoot2.6.x使用PathPatternMatcher匹配路径,Swagger引用的Springfox基于AntPathMatcher匹配路径。匹配方式不同,导致错误。

因此在application.yaml/properties 文件新加。


spring:
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher

3.访问页面为空

你项目中加了拦截器,需要在拦截器相应的放行静态资源。

springboot集成swagger页面空白解决方法_swagger 空白_立码收复恶眛里恳的博客-CSDN博客

猜你喜欢

转载自blog.csdn.net/Qhx20040819/article/details/132367222