springboot快速整合swagger(傻瓜式教学)

本文详细介绍如何在SpringBoot项目中集成Swagger2,包括添加Maven依赖、配置Swagger2、创建测试Controller,以及如何访问和使用Swagger界面进行接口测试。

swagger是一个方便后端编写接口文档的开源项目,并提供界面化测试。

新建springboot项目

  • maven依赖
<!--swagger2-->
<dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-swagger-ui</artifactId>
	<version>2.8.0</version>
</dependency>
<dependency>
	<groupId>io.springfox</groupId>
	<artifactId>springfox-swagger2</artifactId>
	<version>2.8.0</version>
</dependency>
  • 新建配置类
@Configuration
@EnableSwagger2
public class Swagger2Config {

	@Bean
	public Docket createRestApi() {
		
    	ParameterBuilder ticketPar = new ParameterBuilder();
        List<Parameter> pars = new ArrayList<Parameter>();  
    	ticketPar.name("Authorization").description("user token")
    	.modelRef(new ModelRef("string")).parameterType("header") 
    	.required(false).build(); //header中的ticket参数非必填,传空也可�?
    	pars.add(ticketPar.build());    //根据每个方法名也知道当前方法在设置什么参�?
		return new Docket(DocumentationType.SWAGGER_2)
				.apiInfo(apiInfo())
				.select()
				.apis(RequestHandlerSelectors
						.basePackage("com.lenovo.lspcm.controller"))
				.paths(PathSelectors.any()).build()
				.globalOperationParameters(pars)  
                .apiInfo(apiInfo());
	}

	private ApiInfo apiInfo() {
		return new ApiInfoBuilder()
		         //页面标题
                .title("Spring Boot Swagger2 构建RESTful API")
                //条款地址
                .termsOfServiceUrl("https://blog.csdn.net/qq_42476228/article/details/102721788")
                .contact("zwd")
                .version("1.0")
                //描述
                .description("API 描述")
                .build();
	}
}
  • 新建测试controller类
@RestController
@RequestMapping("/api/user/")
@Api(value = "UserController ", tags = { "用户管理模块" })
public class UserController {

    @ApiOperation(value = "接口的功能介绍", notes = "提示接口使用者注意事项")
	@RequestMapping(value = "/users/login", method = RequestMethod.GET)
    public String index(@ApiParam(name = "username", value = "用户名为字符串", required = true)
                        @RequestParam String username) {

        return "hello "+ username;
    }
}

启动项目spring-boot-swagger2,访问 http://localhost:8080/swagger-ui.html
就可以看到你写的接口,并且支持测试。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值