1)在maven项目的pom.xml中引入相关依赖
<!--swagger-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!--swagger-ui-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.github.xiaoymin/knife4j-spring-boot-starter -->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>2.0.9</version>
</dependency>
2)创建Swagger配置依赖,代码如下:
@Configuration@EnableSwagger2@ConditionalOnClass(Docket.class)@EnableKnife4jpublicclassKnife4jConfiguration{@BeanpublicDocketbuildDocket(){returnnewDocket(DocumentationType.SWAGGER_2) .apiInfo(buildApiInfo()) .select()// 要扫描的API(Controller)基础包.apis(RequestHandlerSelectors.basePackage("xxx.controller")) .paths(PathSelectors.any()) .build(); }privateApiInfobuildApiInfo(){Contactcontact=newContact("林木","","xxx");returnnewApiInfoBuilder() .title("智屏小程序说明文档") .description("智屏小程序说明文档") .contact(contact) .version("1.0.0").build(); }}
3)项目模块使用注解【@Api】进行标注,具体方法说明使用 【@ApiOperation】和【@ApiImplicitParam】两个注解
@Api(tags = "商品模块")@Controller@RequestMapping("/product")@CrossOrigin(allowCredentials="true", allowedHeaders = "*")publicclassProductController{/**
* 更新缓存的方法
* product/updateProductInfoCache
*/@ApiOperation(value = "更新缓存方法")@GetMapping("/updateProductInfoCache")publicStringupdateProductInfoCache(Model model){booleanflag=productService.updateProductInfoCache(); model.addAttribute("resultFlag", flag);return"product/updateProductCacheResult"; }/** * 获取商品详情的方法 *@parammodel *@paramcommonId *@return*@throwsException */@ApiOperation(value = "获取商品详情方法")@ApiImplicitParam(name = "commonId",value = "小品商品ID",required = true)@GetMapping("/getProductDetail")publicStringgetProductDetail(Model model,@RequestParam(name="commonId")String commonId)throwsException {ProductInfoViewproductInfoViewFromRedis=(ProductInfoView) redisTemplate.opsForValue().get("ZPSM_PRODUCT_COMMONID_"+commonId); ...return"product/product-detail"; }
至此一个简单的knife4j框架集成就完成了,然后访问项目【ip:端口/doc.html】,例如:http://localhost:8080/doc.html
启动项目看一下效果图: