1.导入依赖
io.springfox springfox-swagger2 io.springfox springfox-swagger-ui
2.添加配置类(注意:如果配置类不在一个模块下,那么要进行包扫描@ComponentScan(" "))
@Configuration @EnableSwagger2 // 开启Swagger功能 public class SwaggerConfiguration { @Bean public Docket buildDocket() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(buildApiInfo()) .select() // 要扫描的API(Controller)基础包 .apis(RequestHandlerSelectors.basePackage("com.heima")) .paths(PathSelectors.any()) .build(); } /** * 构建Api信息 * @return */ private ApiInfo buildApiInfo() { Contact contact = new Contact("黑马程序员","",""); return new ApiInfoBuilder() .title("黑马头条-平台管理API文档") .description("平台管理服务api") .contact(contact) .version("1.0.0").build(); } }
3.controllor标注注解
@RestController @RequestMapping("/api/v1/channel") @Api(tags = "频道管理API") public class WmChannelController { // 注入服务接口 @Autowired private IWmChannelService wMChannelService; /** * 根据名称模糊查询分页列表 * * @param dto * @return */ @PostMapping("/list") @ApiOperation(value = "根据名称模糊查询分页列表", notes = "author:syl") // value指名称 notes 备注 @ApiImplicitParam(name = "dto", value = "查询对象", required = true, dataType = "ChannelDto") public ResponseResult listByName(@RequestBody ChannelDto dto) { return wMChannelService.listByName(dto); } }
4.实体类标注注解
@Data @EqualsAndHashCode(callSuper = true) public class ChannelDto extends PageRequestDto { /** * 频道名称 */ @ApiModelProperty(value = "频道名称") private String name; }
5.访问地址:http://localhost:9001/swagger-ui.html
使用knife4j
1.导入依赖
<dependency> <groupId>com.github.xiaoymin</groupId> <artifactId>knife4j-spring-boot-starter</artifactId> </dependency>
2.添加配置类(注意:1.注释掉swagger配置 2.如果配置类不在一个模块下,那么要进行包扫描@ComponentScan(" "))
@Configuration @EnableSwagger2 @EnableKnife4j @Import(BeanValidatorPluginsConfiguration.class) public class MyKnife4jConfiguration { @Bean(value = "defaultApi2") public Docket defaultApi2() { Docket docket=new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() //这里指定Controller扫描包路径 .apis(RequestHandlerSelectors.basePackage("com.heima")) .paths(PathSelectors.any()) .build(); return docket; } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("黑马头条API文档") .description("黑马头条API文档") .version("1.0") .build(); } }