Swagger结合springboot使用

本文介绍了如何在SpringBoot项目中集成Swagger,包括环境配置、依赖引入、Swagger配置Bean、定义RESTful接口以及Swagger常用注解的使用。通过启用@EnableSwagger2启动Swagger,并通过@Api、@ApiOperation等注解进行接口和参数的文档化描述。启动项目后,访问http://localhost:8080/swagger-ui.html可查看Swagger UI。

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

1.环境


SpringBoot    2.0.4.RELEASE
Swagger    1.7.1
JDK    1.8


2.依赖

<dependency>
	<groupId>com.spring4all</groupId>
	<artifactId>swagger-spring-boot-starter</artifactId>
	<version>1.7.1.RELEASE</version>
</dependency>


3.Swagger配置Bean
@Configuration会被项目启动加载为配置类,等同于XML中配置的beans;
@Bean标注方法等同于XML中配置的bean。

@Configuration
@EnableSwagger2
public class Swagger2Config {
    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.xx.xx.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("xx系统")
                .description("xxx模块")
                .contact("xxxxxx")
                .version("1.0")
                .build();
    }

启动类中加入@EnableSwagger2 代表swagger开启:

@EnableScheduling
@SpringBootApplication
@EnableSwagger2
@EnableCaching
@ComponentScan(basePackages={"com.xx"})
@EnableJpaRepositories
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}


4.定义restful接口

@RestController
@RequestMapping("web/address")
@Api(value="地址管理模块")
public class AddressController {
	@Autowired
	IAddressService addressService;

	@BussinessLog("获取地区")
	@RequestMapping(value = "getList")
	@ApiOperation(value="获取地区",notes="根据id获取地址列表" produces = "application/json",httpMethod="GET")
	public ResponseResult<List<APIAddressResponse>> list(Integer pid) {
		 return ResponseResult.SUCCESS(apiAddressTree);
	}
	
}


6.启动


启动项目访问 http://localhost:8080/swagger-ui.html

这个时候,swagger的ui就展现到了你的面前,和上面的图一样

 

7.Swagger常用注解

用于类

- @Api()  表示标识这个类是swagger的资源 

- @ApiModel() 对类进行说明,用于参数用实体类接收 

- @ApiIgnore()用于类,方法,方法参数 表示这个方法或者类被忽略 

用于方法:
- @ApiOperation()  表示一个http请求的操作 

- @ApiImplicitParam()  表示单独的请求参数 

- @ApiImplicitParams() 包含多个 @ApiImplicitParam

用户多处:
- @ApiParam()用于方法,参数,字段说明; 表示对参数的添加元数据(说明或是否必填等) 

- @ApiModelProperty()用于方法,字段 表示对model属性的说明或者数据操作更改 
 

具体使用举例说明: 
@Api() 
用于类;表示标识这个类是swagger的资源 
tags–表示说明 
value–也是说明,可以使用tags替代 
但是tags如果有多个值,会生成多个list

一张图说明所有问题
 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值