springboot項(xiàng)目中,前后端分離開發(fā)钳踊,前端頁面要調(diào)用后端api處理業(yè)務(wù)就需要知道api接口的詳細(xì)說明衷敌,包括調(diào)用路徑勿侯、調(diào)用方式、入?yún)⒔陕蕖⒊鰠⒌认嚓P(guān)要素助琐。在早些年的時(shí)候,前后端人員都是通過編寫word接口文檔方式進(jìn)行溝通面氓,工作量非常大兵钮,溝通效率也不高。在swigger出現(xiàn)后舌界,開發(fā)人員徹底從編寫word接口文檔中解放出來掘譬,把精力放在具體的業(yè)務(wù)實(shí)現(xiàn)上。
swigger是一款能夠自動(dòng)生成api接口文檔的框架呻拌,我們只需要根據(jù)swigger提供的語言規(guī)范在API接口處添加對(duì)應(yīng)的描述葱轩,它就能自動(dòng)生成接口文檔,并能夠在線查看藐握,大大縮減了前后端開發(fā)人員的溝通成本靴拱。
1.添加swagger依賴
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
2.配置swagger
@Configuration
@EnableSwagger2
public class Swagger2Config {
@Bean
public ApiInfo apiInfo(){
return new ApiInfoBuilder()
.title("xxx林業(yè)平臺(tái)")
.description("xxx林業(yè)平臺(tái)后臺(tái)api接口文檔")
.termsOfServiceUrl("127.0.0.1:9000") //根據(jù)本機(jī)端口配置
.version("1.0")
.build();
}
@Bean
public Docket docket(){
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.cc.app")) //api包路徑
.paths(PathSelectors.regex("/api/.*")) //api的path
.build();
}
}
3.使用swagger注解
通過swagger提供的注解對(duì)api接口進(jìn)行描述,swagger根據(jù)描述生成api接口文檔趾娃。
常用的注解如下:
@Api(value = "/api/jc_sp_line", description = "樣線監(jiān)測(cè)數(shù)據(jù)") 用于類描述
@ApiOperation(value = "根據(jù)ID查詢信息",notes = "根據(jù)ID查詢信息") 用于方法描述
@ApiImplicitParam(name = "params", value = "UID 如:{id:'aa'}" ) 用于參數(shù)字段描述
@ApiImplicitParams({
@ApiImplicitParam(name = "name", value = "姓名"),
@ApiImplicitParam(name = "age", value = "年齡")
}) 用于多個(gè)參數(shù)字段描述
具體代碼使用如下:
/**
* 樣線監(jiān)測(cè)數(shù)據(jù)模塊控制層
* creater shah on 2020/02/05
**/
@Api(value = "/api/jc_sp_line", description = "樣線監(jiān)測(cè)數(shù)據(jù)")
@RestController
@RequestMapping("/api/jc_sp_line")
public class JcSPLineController extends BaseController{
private static Logger logger = LoggerFactory.getLogger(JcSPLineController.class);
@Autowired
public JcSPLineService service;
/**
* 根據(jù)ID查詢信息
* @param uid
* @return
*/
@ApiOperation(value = "根據(jù)ID查詢信息",notes = "根據(jù)ID查詢信息")
@RequestMapping(value = "/findAllByID", method = RequestMethod.GET)
public Object findAllByID(String uid){
JcSPLine bean=service.findInfoByID(uid);
return RtnData.ok(bean);
}
@ApiOperation(value = "單筆刪除樣線監(jiān)測(cè)數(shù)據(jù)",notes = "單筆刪除樣線監(jiān)測(cè)數(shù)據(jù)")
@ApiImplicitParam(name = "params", value = "UID 如:{id:'aa'}" )
@RequestMapping(value = "/delete",method = RequestMethod.POST)
public RtnData delete(@RequestBody Map params){
service.delete((String) params.get("id"));
return RtnData.ok("success");
}
4.查看swagger生成的接口文檔
項(xiàng)目啟動(dòng)后缭嫡,訪問地址:http://localhost:9000/swagger-ui.html缔御,可以看到API文檔界面:
點(diǎn)開一個(gè)controller條目抬闷,可以看到API接口列表:
點(diǎn)開一個(gè)接口方法,可以看到接口參數(shù)詳情:
是不是很詳細(xì)耕突,是不是很方便s猿伞!眷茁!
*媽媽以后再也不用擔(dān)心我跟前端妹子吵架了炕泳,好開心!