springboot集成swagger

1,创建新的springboot web项目

2,引入相关的swagger依赖(pom.xml)

         <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>3.0.0</version>
            <!--移除swagger-models 1.5.20 依赖,存在Swagger2异常:Illegal DefaultValue null for parameter type integer问题-->
            <exclusions>
                <exclusion>
                    <groupId>io.swagger</groupId>
                    <artifactId>swagger-annotations</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>io.swagger</groupId>
                    <artifactId>swagger-models</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

        <!--重新引入swagger-models和swagger-annotations 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>


        <!--springfox-boot-starter包含了以下两个依赖,所以不需要重复引入-->
        <!--
        <dependency>
        	<groupId>io.springfox</groupId>
        	<artifactId>springfox-swagger-ui</artifactId>
        	<version>3.0.0</version>
        </dependency>

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

2,创建实体类  model/User.java


public class Users {
    private Integer id;
    private String nick;
    private String phone;
    private String password;
    private String email;
    private String account;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getNick() {
        return nick;
    }

    public void setNick(String nick) {
        this.nick = nick;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getAccount() {
        return account;
    }

    public void setAccount(String account) {
        this.account = account;
    }
}

3,创建swagger测试的controller类  controller/SwaggerController.java



@Api(tags = "springboot使用swagger测试")
@RestController
public class SwaggerController {

    @ApiOperation(value = "获取用户信息", notes = "根据id来获取用户详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "path", name = "id", value = "用户ID",  dataType = "Integer"),
            @ApiImplicitParam(paramType = "path", name = "status", value = "用户状态", dataType = "Integer"),
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "请求成功"),
            @ApiResponse(code = 400, message = "缺少必要的请求参数"),
            @ApiResponse(code = 401, message = "请求路径没有相应权限"),
            @ApiResponse(code = 403, message = "请求路径被隐藏不能访问"),
            @ApiResponse(code = 404, message = "请求路径没有或页面跳转路径不对"),
            @ApiResponse(code = 405, message = "请求方法不支持"),
    })

    @RequestMapping(value = "/swagger/user/{id}/{status}", method = RequestMethod.GET)
    public @ResponseBody
    Users getUserInfo(@PathVariable("id") Integer id, @PathVariable("status") Integer status) {
        Users users = new Users();
        users.setId(id);
        users.setNick("zs");
        users.setPhone("1370000000");
        users.setPassword("******");
        users.setEmail("zs@163.com");
        users.setAccount("NO68958886878664");
        return users;
    }

    @ApiOperation(value = "添加用户信息", notes = "将用户信息提交保存到数据库")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body", name = "users", value = "用户对象", dataTypeClass = Users.class)
    })
    @ApiResponses({
            @ApiResponse(code = 400, message = "缺少必要的请求参数"),
            @ApiResponse(code = 401, message = "请求路径没有相应权限"),
            @ApiResponse(code = 403, message = "请求路径被隐藏不能访问"),
            @ApiResponse(code = 404, message = "请求路径没有或页面跳转路径不对"),
            @ApiResponse(code = 405, message = "请求方法不支持"),
    })
    @RequestMapping(value = "/swagger/users", method = RequestMethod.POST)
    public @ResponseBody Users postUserInfo(@RequestBody Users users) {
        return users;
    }

    @ApiOperation(value = "修改用户信息", notes = "将用户信息修改保存到数据库")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body", name = "users", value = "用户对象", dataTypeClass = Users.class)
    })
    @ApiResponses({
            @ApiResponse(code = 400, message = "缺少必要的请求参数"),
            @ApiResponse(code = 401, message = "请求路径没有相应权限"),
            @ApiResponse(code = 403, message = "请求路径被隐藏不能访问"),
            @ApiResponse(code = 404, message = "请求路径没有或页面跳转路径不对"),
            @ApiResponse(code = 405, message = "请求方法不支持"),
    })
    @RequestMapping(value = "/swagger/users", method = RequestMethod.PUT)
    public @ResponseBody Users putUserInfo(@RequestBody Users users) {
        return users;
    }

    @ApiOperation(value = "删除户信息", notes = "将用户信息从数据库删除")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "id", value = "用户ID", dataType = "Integer")
    })
    @ApiResponses({
            @ApiResponse(code = 400, message = "缺少必要的请求参数"),
            @ApiResponse(code = 401, message = "请求路径没有相应权限"),
            @ApiResponse(code = 403, message = "请求路径被隐藏不能访问"),
            @ApiResponse(code = 404, message = "请求路径没有或页面跳转路径不对"),
            @ApiResponse(code = 405, message = "请求方法不支持"),
    })

4,创建config/SwaggerConfig.java


@EnableSwagger2 //开启Swagger2的支持
@Configuration //配置类,== applicationContext.xml
@EnableWebMvc
public class SwaggerConfig implements WebMvcConfigurer {


    /**
     * 在spring容器配置一个bean对象
     *
     * @Bean 等价于 <bean id="createRestApi" class="xxxx.Docket">
     *
     * @return
     */
    @Bean
    public Docket docket() {
        //链式编程(构建器模式),基本是固定;
        return new Docket(DocumentationType.SWAGGER_2)
                .enable(true)//可以开启或关闭swagger文档
                .apiInfo(apiInfo())
                .select()
                //.apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
                .apis(RequestHandlerSelectors.basePackage("com.bsj.springboot.controller"))
                //.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))//扫描有ApiOperation注解的方法
                //.paths(PathSelectors.any())
                //.paths((s) -> !s.contains("/login")) //不包含login登录的路径
                .build();
    }

    /**
     * 创建api的基本信息
     *
     * @return
     */
    private ApiInfo apiInfo() {
        //链式编程(构建器模式),基本是固定;
        return new ApiInfoBuilder()
                .title("用户账号中心接口文档")
                .description("集成Swagger2构建RESTful APIs")
                .termsOfServiceUrl("http://www.baidu.com/")
                .contact(new Contact("cat","http://www.baidu.com","zs@163.com"))
                .license("采用 Apache 2.0 开源许可证")
                .licenseUrl("http://http://www.baidu.com/licence.txt")
                .version("1.0.0")
                .build();
    }

    //解决  No mapping for GET /favicon.ico 访问静态资源图标
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/static/")
                .addResourceLocations("classpath:/META-INF/resources/");
    }
}

5,配置application.properties

#配置端口号
server.port=9090
#配置上下文根
server.servlet.context-path=/app

6,启动

7,测试

浏览器输入:localhost:9090/app/swagger/user/1/3

 浏览器输入swagger-ui地址:http://localhost:9090/app/swagger-ui/index.html

8,排坑:

        ①建议依赖使用 下面的springfox-boot-starter,来代替 springfox-swagger-ui和springfox-swagger2,同时swagger-ui地址只能是:http://localhost:端口号/上下文根/swagger-ui/index.html

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>3.0.0</version>
            <!--移除swagger-models 1.5.20 依赖,存在Swagger2异常:Illegal DefaultValue null for parameter type integer问题-->
            <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>

②:报错java.lang.NumberFormatException: For input string: ""

2022-08-02 10:29:22.482  WARN 14024 --- [nio-9090-exec-5] i.s.m.p.AbstractSerializableParameter    : Illegal DefaultValue null for parameter type integer

是因为

springfox-swagger2中集成了swagger-models 1.5.20 依赖,而这个版本是有问题的,所以排除swagger-models 和swagger-annotations的1.5.20 版本,换用1.5.21版本

③:SwaggerConfig类

要实现 WebMvcConfigurer

并重写 addResourceHandlers方法,

并开启注解@EnableWebMvc,

否则控制台会一直报错:

org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException

Caused by: java.lang.NullPointerException: null

或者

No mapping for GET /null/swagger/user/

9,Swagger常用注解:

@Api:用在类上,说明该类的作用;

@ApiOperation:用在方法上,说明方法的作用;

@ApiImplicitParams:用在方法上包含一组参数说明;

@ApiImplicitParam:用在@ApiImplicitParams注解中,指定一个请求参数的各个方面:

paramType:参数放在哪个地方;

header-->请求参数的获取:@RequestHeader

query-->请求参数的获取:@RequestParam

path-->请求参数的获取:@PathVariable (用于restful接口)

body(不常用)

form(不常用)

name: 参数名;

dataType:参数类型;

required:参数是否必须传;

value:参数的意思;

defaultValue:参数的默认值;

@ApiResponses:用于表示一组响应;

@ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息;

code:数字,例如400

message:信息,例如 "请求参数不合法"

response:抛出异常的类

@ApiIgnore使用该注解忽略这个API,在页面上不显示;

@ApiModel:描述一个Model的信息;

@ApiModelProperty:描述一个model的属性;

注解可参考官方:https://github.com/swagger-api/swagger-core/wiki/Annotations 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值