1、添加依赖:
<!--Swagger2-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
2、配置类Swagger2Config.java
package com.xukun.springcloud.config;
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;
@Configuration
@EnableSwagger2
public class Swagger2Confg {
//api接口包扫描路径
private static final String SWAGGER_SCAN_BASE_PACKAGE = "com.xukun.springcloud.controller";
private static final String VERSION = "1.0.0";
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage(SWAGGER_SCAN_BASE_PACKAGE))
.paths(PathSelectors.any()) // 可以根据url路径设置哪些请求加入文档,忽略哪些请求
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("支付服务") //设置文档的标题
.description("支付服务 API 接口文档") // 设置文档的描述
.version(VERSION) // 设置文档的版本信息-> 1.0.0 Version information
.build();
}
}
3、API接口编写
package com.xukun.springcloud.controller;
import com.xukun.springcloud.exception.ResultData;
import com.xukun.springcloud.exception.ResultDataUtils;
import com.xukun.springcloud.model.Payment;
import com.xukun.springcloud.service.PaymentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@Api(tags = "支付服务接口")
@RestController
@RequestMapping("/payment")
public class PaymentController {
@Autowired
private PaymentService paymentService;
@ApiOperation("根据id删除支付信息")
@DeleteMapping("/delete/{id}")
public ResultData deleteById(@PathVariable Long id) {
return ResultDataUtils.success(paymentService.deleteById(id));
}
@ApiOperation("添加支付信息")
@PostMapping("/insert")
public ResultData insert(@RequestBody Payment record) {
int count = paymentService.insert(record);
if (count == 1) {
return ResultDataUtils.success(count);
}
return ResultDataUtils.fail();
}
@ApiOperation("根据id获取支付信息")
@GetMapping("/get/{id}")
public ResultData selectById(@PathVariable Long id) {
return ResultDataUtils.success(paymentService.selectById(id));
}
@ApiOperation("根据id更新支付信息")
@PostMapping("/update")
public ResultData updateById(@RequestBody Payment record) {
int count = paymentService.updateById(record);
if (count == 1) {
return ResultDataUtils.success(count);
}
return ResultDataUtils.fail();
}
}
4、在浏览器访问
ip:port/swagger-ui.html