【水滴石穿】SpringBoot 集成Swagger

SpringBoot 集成Swagger

Swagger 可以使你的restful接口自动生成接口文档,方便查看与测试,下面是一些具体步骤:

1、引入swagger相关依赖

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

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>

2、添加配置类

@Configuration
@EnableSwagger2
public class SwaggerConfiguration {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //选择controller包
                .apis(RequestHandlerSelectors.basePackage("com.xxx.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                //自定义信息可按需求填写
                .title("API")
                .description("接口文档")
                .termsOfServiceUrl("http://localhost/web/")
                .contact(new Contact("author", "", ""))
                .version("1.0")
                .build();
    }
}

3、常用的一些注解

最常用的5个注解 主要用来对接口或参数做备注信息

@Api:修饰整个类,描述Controller的作用

@ApiOperation:描述一个类的一个方法,或者说一个接口

@ApiParam:单个参数描述

@ApiModel:用对象来接收参数

@ApiProperty:用对象接收参数时,描述对象的一个字段

4、注解使用demo

@Api(value="用户模块")
@RestController
@RequestMapping("user")
public class UserController {
    
    @Autowired
    private UserService userService;

    @ApiOperation(value = "根据用户id查询用户")
    @GetMapping("find/{id}")
    public User findById(@ApiParam Integer id) {
        User user = userService.findById(id);
        return user;
    }
    }

5、启动和访问

启动application 并访问http://localhost:8088/swagger-ui.html,根据自身项目地址而定

6、常见问题

访问swagger-ui.html时,弹出错误提示框

Unable to infer base url.
This is common when using dynamic servlet registration or when the API is behind an API Gateway.
The base url is the root of where all the swagger resources are served. For e.g. if the api is available at http://example.org/api/v2/api-docs then the 				base url is http://example.org/api/.
Please enter the location manually:

可以参考未扫描到swagger注解解决办法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值