SpringBoot---Swagger文档管理应用

本文介绍了如何在SpringBoot项目中集成Swagger,包括添加依赖、创建独立Maven子模块、配置Swagger、以及如何在工程中应用Swagger配置。通过在控制器和实体类中使用Swagger注解,实现详细的API文档管理。

1、添加依赖

<dependencies>
		<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>
	</dependencies>

2、创建独立的Maven子模块

a、Swagger配置类

package com.imooc;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

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.ApiSelectorBuilder;
import springfox.documentation.spring.web.plugins.Docket;

@Configuration
//@EnableConfigurationProperties(SwaggerInfo.class)
public class SwaggerConfig {
	
	@Autowired
	private SwaggerInfo swaggerInfo;

	@Bean
	public Docket controllerApi(){
		System.out.println("======swaggerInfo====="+swaggerInfo);
		Docket docket = new Docket(DocumentationType.SWAGGER_2)
				.groupName(swaggerInfo.getGroupName()) // 分组名
				.apiInfo(apiInfo());
		ApiSelectorBuilder builder = docket.select();
		if(!StringUtils.isEmpty(swaggerInfo.getBasePackage())){
			builder = builder.apis(RequestHandlerSelectors.basePackage(swaggerInfo.getBasePackage())); // 筛选显示接口
		}
		if(!StringUtils.isEmpty(swaggerInfo.getAntPath())){
			builder = builder.paths(PathSelectors.ant(swaggerInfo.getAntPath()));
		}
		
		return builder.build();
	}
	
	public ApiInfo apiInfo(){
		return new ApiInfoBuilder()
				.title(swaggerInfo.getTitle())
				.description(swaggerInfo.getDescription())
				.termsOfServiceUrl("http://springfox.io")
				.contact("imooc")
				.license(swaggerInfo.getLicense())
				.version("2.0")
				.build();
	}
}

属性配置类

package com.imooc;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * Swagger配置信息
 * @author zemel
 *
 */
@Component
@ConfigurationProperties(prefix="swagger", ignoreUnknownFields = true)
public class SwaggerInfo {

	private String groupName = "controller";
	private String basePackage;
	private String antPath;
	private String title = "HTTP API";
	private String description = "管理端接口";
	private String license = "Apache License Version 2.0";
	public String getGroupName() {
		return groupName;
	}
	public void setGroupName(String groupName) {
		this.groupName = groupName;
	}
	public String getBasePackage() {
		return basePackage;
	}
	public void setBasePackage(String basePackage) {
		this.basePackage = basePackage;
	}
	public String getAntPath() {
		return antPath;
	}
	public void setAntPath(String antPath) {
		this.antPath = antPath;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
	public String getLicense() {
		return license;
	}
	public void setLicense(String license) {
		this.license = license;
	}
	@Override
	public String toString() {
		return "SwaggerInfo [groupName=" + groupName + ", basePackage=" + basePackage + ", antPath=" + antPath
				+ ", title=" + title + ", description=" + description + ", license=" + license + "]";
	}
	
}

b、其他工程应用方法有三种

1)一种直接在App.java中使用@Import注解导入配置类

@SpringBootApplication
//@EnableMySwagger
@Import(SwaggerConfig.class)
public class App {

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

2)编写@Enable*的注解,在App.java中启用

package com.imooc;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import org.springframework.context.annotation.Import;

import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Retention(value = java.lang.annotation.RetentionPolicy.RUNTIME)
@Target(value = { java.lang.annotation.ElementType.TYPE })
@Documented
@Import({SwaggerConfig.class})
@EnableSwagger2 // 组合注解
public @interface EnableMySwagger {

}
@SpringBootApplication
@EnableMySwagger
public class App {

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

3)在resource/META_INF/spring.factories下配置Config类

org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.imooc.SwaggerConfig

3、在应用Swagger工程配置文件(application.properties)

# 配置swagger
swagger.groupName=manager
swagger.basePackage=com.imooc.controller

4、Swagger功能使用

控制器,主要注释带@ApiXX

package com.imooc.controller;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.imooc.entity.Product;
import com.imooc.service.ProductService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping("/products")
@Api(tags="order", description="产品相关")
public class ProductController {

	private static Logger log = LoggerFactory.getLogger(ProductController.class);
 
	@Autowired
	private ProductService productService;
	
	@ApiOperation(notes="根据队员业务规划添加相应产品", value="创建产品")
	@PostMapping
	public Product addProduct(@RequestBody Product product){
		
		log.debug("创建产品,参数:{}",product);
		
		Product result = productService.addProduct((product));
		
		log.debug("创建产品,结果:{}",result);
		
		return result;
	}
	
	@GetMapping("/{id}")
	public Product findOne(@PathVariable String id){
		log.debug("查询单个产品,id={}", id);
		
		Product product = productService.findOne(id);
		
		log.debug("查询单个产品,结果={}", product);
		return product;
	}
	
	@GetMapping
	public Page<Product> query(String ids, BigDecimal minRewardRate, BigDecimal maxRewardRate, String status, 
			@RequestParam(defaultValue = "0")int pageNum, @RequestParam(defaultValue = "10") int pageSize){
		
		log.info("查询产品,idList={},minRewardRate={},maxRewardRate={},statusList={},pageNum={},pageSize={}",ids, minRewardRate,maxRewardRate,status,pageNum,pageSize);
		
		List<String> idList = null;
		List<Integer> statusList = null;
		if(!StringUtils.isEmpty(ids)){
			idList = Arrays.asList(ids.split(","));
		}
		if(!StringUtils.isEmpty(statusList)){
			String[] statusStr = status.split(",");
//			statusStr.m
			Integer[] statusInt = new Integer[statusStr.length];
			for(int i=0; i<statusStr.length; i++){
				statusInt[i] = Integer.parseInt(statusStr[i]);
			}
			statusList = Arrays.asList(statusInt);
		}
		
		Pageable pageable = PageRequest.of(pageNum, pageSize);
		Page<Product> page = productService.query(idList, minRewardRate, maxRewardRate, statusList, pageable);
		log.info("查询产品,结果={}", page);
		
		return page;
	}
	
}

实体类中使用

@ApiModel(value="ppp", description="产品模型")
@Entity
@Table(name="product_t")
public class Product {
	
	@Id
	@Column(name="id",columnDefinition="varchar(50) comment '产品编号'")
	private String id;
	
	@Column(name="name",columnDefinition="varchar(50) not null default '' comment '产品名称'")
	private String name;
	
	/**
	 * @see com.imooc.entity.enums.ProductStatus
	 */
	@ApiModelProperty(value="状态", dataType="com.imooc.entity.enums.ProductStatus")
	@Column(name="status",columnDefinition="smallint(6) not null default 0 comment '状态,1:审核中、2:销售中、3:暂停销售、4:已结束' ")
	private Integer status;
}

 

 

 

 

 

 

### 如何在 Spring Boot 中集成 Swagger #### 添加依赖项 为了使 Spring Boot 项目能够支持 Swagger,需向项目的 `pom.xml` 文件中添加相应的 Maven 依赖。对于 Spring Boot 版本 3.x 及更高版本而言,推荐使用 `springdoc-openapi-starter-webmvc-ui` 来替代旧版的 swagger 相关库。 ```xml <dependency> <groupId>org.springdoc</groupId> <artifactId>springdoc-openapi-starter-webmvc-ui</artifactId> <version>2.0.2</version><!-- 确认此版本兼容当前使用的Spring Boot版本 --> </dependency> ``` #### 配置应用属性文件 通常情况下,默认设置已经足够让 Swagger 正常工作;然而如果想要自定义路径或者其他行为,则可以在 application.properties 或者 application.yml 文件里加入特定参数: ```properties # application.properties 示例 springdoc.api-docs.path=/v3/api-docs springdoc.swagger-ui.path=/swagger-ui.html ``` #### 启动并验证 完成上述操作之后重新编译运行程序,在浏览器地址栏输入如下链接即可打开 Swagger UI 页面浏览 API 文档[^1]。 http://localhost:8080/swagger-ui/index.html #### 更复杂的场景处理 当遇到更加复杂的应用需求时——比如安全机制设定或是多个 API 组管理等方面的要求,应当查阅 springdoc-openapi 官方指南获取更多指导信息以便做出适当调整[^3]。 ```java // Java代码片段用于展示如何通过@Bean注解注册组件 import org.springframework.context.annotation.Bean; ... @Bean public OpenAPI customOpenAPI(){ return new OpenAPI() .info(new Info().title("Sample Application API").description("This is a sample Spring Boot RESTful service using springdoc-openapi and OpenAPI 3.").version("v0.0.1")); } ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值