Swagger 简单使用

本文介绍了如何在Spring项目中集成Swagger,包括添加依赖、配置Swagger类以及使用注解进行API文档的创建。通过在类和方法上添加@Api和@ApiOperation等注解,详细说明了如何标记接口功能。最后,给出了访问Swagger UI的URL,便于测试和查看API文档。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、在项目中添加依赖:

		<!-- swagger核心组件,在代码配置swagger时会依赖到它 -->
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger2</artifactId>
			<version>2.9.2</version>
		</dependency>
		<!-- swagger的用户界面,用于展示api接口文档 -->
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger-ui</artifactId>
			<version>2.9.2</version>
		</dependency>

2、创建Swagger的配置类:

package com.soft.configer;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * Created by Administrator on 2020/10/17 0017.
 */
@Configuration
@EnableSwagger2
public class SpringfoxSwagger2Config {
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.soft.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Swagger")
                .description("更多内容请咨询开发者 zc")
                .termsOfServiceUrl("http://www.baidu.com")
                .contact("zc")
                .version("1.0")
                .build();
    }

}

3、自行添加注解:
类上添加注解:
@Api(value = “字典操作接口”,tags = {“字典常量操作”})
方法上添加注解:@ApiOperation(value = “新增及更新字典”,notes = “对象包含ID时为更新,不包含ID时为新增”)
@ApiImplicitParam(name = “user”,value = “字典对象,详细请查看对象属性”,required = true,dataType = “User”)
@PostMapping("/update")
public String update(@RequestBody User user)
4、访问:http://localhost:8800/swagger-ui.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值