spring boot 之集成swagger定义API文档

前提是建一个spring boot项目,下面为使用swagger定义API文档的主要流程:

1、加入swagger依赖springfox-swagger2、springfox-swagger-ui,加入方法如下图所示

引入依赖后,pom.xml如下

<!--swagger2  -->
		<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、相关参数配置application.yml

swagger:
  enabled: true

3、在启动类相同目录下定义Swagger配置类



import org.springframework.beans.factory.annotation.Value;
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;

@Configuration
public class Swagger2 {
	
	//是否开启swagger
	@Value(value = "${swagger.enabled}")
	Boolean swaggerEnabled;
		
	@Bean
	public Docket createRestApi() {
		return new Docket(DocumentationType.SWAGGER_2)
				.apiInfo(apiInfo())
				.enable(swaggerEnabled)
				.select()
				.apis(RequestHandlerSelectors.basePackage("需要使用文档的接口对应的包路径"))
				.paths(PathSelectors.any())
				.build();
	}
	
	private ApiInfo apiInfo() {
		return new ApiInfoBuilder()
				//页面标题
				.title("页面标题")
				.description("描述")
				.version("1.0")
				.build();
	}

}

四、在启动类上添加注解@EnableSwagger2

五、在需要文档的接口类上添加注解,如下

import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

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

@Api("缴费人信息查询入口")
@Controller
public class PayInfoController {
	
	@ApiOperation(value="缴费人信息查询",notes="缴费人信息查询入口")
	@ApiImplicitParams({@ApiImplicitParam(name="name",value="姓名",required=true,paramType="String",dataType="String"),
		@ApiImplicitParam(name="certNo",value="证件号",required=true,paramType="String"),
		@ApiImplicitParam(name="certType",value="证件类型",required=true,paramType="String")})
	@PostMapping("/payInfo")
	public ModelAndView index(
			@RequestParam(required=true) String name,
			@RequestParam(required=true) String certNo,
			@RequestParam(required=true) String certType) {
		Map map = new HashMap();
		map.put("name", name);
		map.put("certNo", certNo);
		map.put("certType", certType);
		
		//查询
		
		return new ModelAndView("html/payinfo",map);
	} 
}

六、访问http://项目路径/swagger-ui.html

猜你喜欢

转载自blog.csdn.net/u014165193/article/details/84972386
今日推荐